﻿using Abp.Application.Services.Dto;
using Abp.Authorization.Users;
using Abp.Collections.Extensions;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Abp.Organizations;
using Abp.Runtime.Session;
using Abp.UI;
using Camc.Quality.Authorization.Users;
using Camc.Quality.Common;
using Camc.Quality.DataDictionary;
using Camc.Quality.IOperationHistory;
using Camc.Quality.Materials;
using Camc.Quality.Materials.Dto;
using Camc.Quality.OperationHistory;
using Camc.Quality.ProductionPlan;
using Camc.Quality.StoreManagement.SoreModel.Dto;
using Camc.Quality.StoreManagement.StoragePut;
using Camc.Quality.StoreManagement.StoragePut.Dto;
using Camc.Quality.StoreManagement.StoreInterface;
using Camc.Quality.SystemManagement;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static Camc.Quality.StoreManagement.StoreEnum;

namespace Camc.Quality.StoreManagement.StoraePut
{
    public class StorePutAppService : QualityAppServiceBase
    {
        private readonly IStoreHttp _storeHttp = new StoreHttp();
        private readonly IRepository<StorePutContent, Guid> _storePutContentRepository;
        private readonly IRepository<MaterialsContent, Guid> _materialsContentRepository;
        private readonly CodeFormatDescAppService _codeFormatDescAppServiceRepository;
        private readonly IAbpSession _abpSession;
        private readonly IRepository<User, long> _userRepository;
        private readonly IOperationHistoryAppService _iOperationHistoryAppService;
        private readonly IRepository<MaterialsNode, Guid> _materialsNodeRepository;
        private readonly IRepository<Sys_Code, Guid> _sysCodeRepository;
        private readonly MaterialsAppService _materialsAppServiceRepository;
        private readonly IRepository<OrganizationUnit, long> _organizationUnitRepository;
        private readonly IRepository<StoreStock, Guid> _storeStockRepository;
        private readonly IRepository<StoreStockContent, Guid> _storeStockContentRepository;
        private readonly IRepository<UserOrganizationUnit, long> _userOrganizationUnitRepository;
        private readonly IRepository<StorePutRecord, Guid> _storePutRecordRepository;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly SysCodeAppService _sysCodeAppServiceRepository;
        private readonly IStoreImportToTable _storeImportToTable = new StoreImportToTable();
        private readonly IRepository<StoreContent, Guid> _storeContentrepository;
        private readonly StoreFunctionsAppService _storeFunctionsAppServicepository;
        CommonAppService _commonAppServiceRepository;
        private readonly IRepository<StandardDrawingNo, Guid> _standardDrawingNoRepository;
        private readonly IRepository<MakeTask, Guid> _makeTaskRepository;
        public StorePutAppService(IRepository<StorePutContent, Guid> storePutContentRepository,
                                  IRepository<MaterialsContent, Guid> materialsContentRepository,
                                  CodeFormatDescAppService codeFormatDescAppServiceRepository,
                                  IAbpSession abpSession,
                                  IOperationHistoryAppService iOperationHistoryAppService,
                                  IRepository<User, long> userRepository,
                                  IRepository<MaterialsNode, Guid> materialsNodeRepository,
                                  IRepository<Sys_Code, Guid> sysCodeRepository,
                                  MaterialsAppService materialsAppServiceRepository,
                                  IRepository<OrganizationUnit, long> organizationUnitRepository,
                                  IRepository<StoreStock, Guid> storeStockRepository,
                                  IRepository<StoreStockContent, Guid> storeStockContentRepository,
                                  IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository,
                                  IRepository<StorePutRecord, Guid> storePutRecordRepository,
                                  IUnitOfWorkManager unitOfWorkManager,
                                  SysCodeAppService sysCodeAppServiceRepository,
                                  IRepository<StoreContent, Guid> storeContentrepository,
                                  StoreFunctionsAppService storeFunctionsAppServicepository,
                                  CommonAppService commonAppServiceRepository,
                                  IRepository<StandardDrawingNo, Guid> standardDrawingNoRepository,
                                  IRepository<MakeTask, Guid> makeTaskRepository
           )
        {
            // this._storeHttp = storeHttp;
            _storePutContentRepository = storePutContentRepository;
            _materialsContentRepository = materialsContentRepository;
            _codeFormatDescAppServiceRepository = codeFormatDescAppServiceRepository;
            _abpSession = abpSession;
            _iOperationHistoryAppService = iOperationHistoryAppService;
            _userRepository = userRepository;
            _materialsNodeRepository = materialsNodeRepository;
            _sysCodeRepository = sysCodeRepository;
            _materialsAppServiceRepository = materialsAppServiceRepository;
            _organizationUnitRepository = organizationUnitRepository;
            _storeStockRepository = storeStockRepository;
            _storeStockContentRepository = storeStockContentRepository;
            _userOrganizationUnitRepository = userOrganizationUnitRepository;
            _storePutRecordRepository = storePutRecordRepository;
            _unitOfWorkManager = unitOfWorkManager;
            _sysCodeAppServiceRepository = sysCodeAppServiceRepository;
            _storeContentrepository = storeContentrepository;
            _storeFunctionsAppServicepository = storeFunctionsAppServicepository;
            _commonAppServiceRepository = commonAppServiceRepository;
            _standardDrawingNoRepository = standardDrawingNoRepository;
            _makeTaskRepository = makeTaskRepository;
        }
        /// <summary>
        /// 合格证入库模态框通过第三方接口获取仓库相关信息
        /// </summary>
        /// <param name = "input" ></param>
        /// <returns ></returns>
        public async Task<StorePutModelContentDto> GetCertificateInfoByCerCode(StorePutEditConditionDto input)
        {
            if (!string.IsNullOrEmpty(input.QualifiedNumber))
            {
                try
                {
                    StorePutModelContentDto storePutModelContentDto = new StorePutModelContentDto();
                    //string certificateJson = PostStoreApp("http://10.19.1.121:31173/learun/adms/qccardapi/GetCertificateByCerCode?cerCod=" + input.QualifiedNumber, "");
                    string certificateJson = "{ \"code\":200, \"info\":\"响应成功\", \"data\":{ \"Certificate\":{ \"F_CertificateId\":\"96a0f9cd-bc52-4d6d-8579-97de4885822e\", \"F_CompanyId\":\"4a31e801-07a8-41e7-bf72-bc4300118bf1\", \"F_DepartmentId\":\"84e6450a-30d6-4744-871b-2d6a9de03860\", \"F_CreateDate\":\"2021-10-15 10:18:35\",\"F_CreateUserId\":\"7e012777-f4ed-4f42-b653-a9c79f1dbc50\",\"F_CreateUserName\":\"王建鹏\",\"F_ModifyDate\":\"2021-10-15 14:13:40\",\"F_ModifyUserId\":\"3883e198-10c7-442d-ae96-ec772f38a3cf\",\"F_ModifyUserName\":\"孙绪龙\",\"F_SortCode\":0,\"F_DeleteMark\":0,\"F_EnabledMark\":1,\"F_Workshop\":\"51\",\"F_WorkshopName\":\"51车间\",\"F_QcCardId\":\"d19fff19-e063-43ad-ba5c-568becce4938\",\"Amount\":\"1\",\"CertificateCode\":\"5121003676\",\"KaiZhengPerson\":\"王建鹏\",\"KaiZhengDate\":\"2021-10-15\",\"TechFileCode\":null,\"Remark\":null,\"JianNum\":\"\",\"BringType\":null,\"CerSpecParam\":null,\"UnitPrice\":null,\"XzCertificatCode\":\"5821007501,J-DC2108254633-10\",\"ProduceType\":\"1\",\"CerBatch\":null,\"StoreAmount\":\"1\",\"UseableAmount\":\"1\",\"Marker\":\"2\",\"TemplateId\":\"2302-2008\",\"IsRepair\":\"0\",\"InceptWorkshop\":\"57\",\"SubmitPerson\":\"姜述伟\",\"SubmitDate\":\"2021-10-15\",\"ProduceWorkShop\":\"51\",\"CerQuality\":\"1\",\"LeiBie\":null,\"KeepPosition\":null,\"Accepter\":\"孙绪龙\",\"AccepterDate\":\"2021-10-15\",\"IsBanchengpin\":\"1\",\"IsVirtual\":\"1\",\"UseableJianNum\":\"\",\"MaterialCode\":null,\"MaterialCodeJt\":null,\"QcCardCode\":\"5121003033\",\"Faci\":null, \"WusunReportCode\":null } } }";
                    //string certificateJson = "{ \"code\":200, \"info\":\"响应成功\", \"data\":{ }}";
                    CertificateDto certificateDto = new CertificateDto();
                    SysCodeDto sysCodeDto = new SysCodeDto();
                    //格式化json成对象数组l
                    certificateDto = JsonConvert.DeserializeObject<CertificateDto>(certificateJson);
                    if (certificateDto.data.Certificate != null)
                    {
                        //string qcCardJson = PostStoreApp("http://10.19.1.121:31173/learun/adms/qccardapi/GetQcCardByCardCode?cardcode=" + certificateDto.data.Certificate.QcCardCode, "");
                        string qcCardJson = "{ \"code\":200, \"info\":\"响应成功\", \"data\":{ \"QcCard\":{\"F_QcCardId\":\"d19fff19-e063-43ad-ba5c-568becce4938\",\"F_CompanyId\":\"4a31e801-07a8-41e7-bf72-bc4300118bf1\",\"F_DepartmentId\":\"a80eacf6-7365-4814-84ba-066e4487720c\",\"F_CreateDate\":\"2021-09-11 14:29:47\",\"F_CreateUserId\":\"f2c0348b-6fcc-4fa0-9241-ea182dc7a5c3\",\"F_CreateUserName\":\"姜述伟\",\"F_ModifyDate\":\"2021-10-15 10:53:14\",\"F_ModifyUserId\":\"f2c0348b-6fcc-4fa0-9241-ea182dc7a5c3\",\"F_ModifyUserName\":\"姜述伟\",\"F_SortCode\":null,\"F_DeleteMark\":0,\"F_EnabledMark\":1,\"F_Workshop\":\"51\",\"F_WorkshopName\":\"51车间\",\"F_QcCardTempletId\":\"3ddc9209-1e80-45f0-8840-4c8e41fdf2c5\",\"F_ProduceTaskItemId\":\"26db005f-c659-4a79-b17a-c1faad9c0408\",\"CertificateCode\":\"5121003676\",\"Channel\":\"51-58-51-57\",\"DrawingLastDate\":\"\",\"DrawingNumber\":\"M5*M6Q/Y94.76-05A-2001    123\",\"LastFenKaCode\":null,\"PlanAmount\":1,\"ProcessKind\":\"机加\",\"ProduceAmount\":1,\"ProductModel\":\"CZ-7系列\",\"ProductName\":\"脱插垫板\",\"ProductNumber\":null,\"QcCardCode\":\"5121003033\",\"state\":4,\"TaskNumber\":\"42AS14-51-0007-J-A\",\"TechnicNumber\":null,\"BatchNum\":null,\"PieceNum\":null,\"Turnover\":\"\",\"Stockpile\":\"\",\"VerifyCycle\":null,\"CardType\":\"1\",\"Schedule\":\"2021-08-31\",\"Checker\":\"王建鹏 2021-10-15\",\"ProducePerson\":\"泽川\",\"SectionChief\":\"高军\",\"OutPutTable\":\"2201-2008\",\"MainWorkshop\":\"51\",\"PhaseSign\":\"S\",\"NeedForm\":\";6-1;\",\"ProductBatchNumber\":\"01\",\"NonmetalDate\":\"\",\"TechnicInfo\":\"李洋2021-07-27\",\"AttemperInfo\":\"姜述伟2021-09-11\",\"TaskRemark\":\"根据FP51-210059报废补投\",\"ShopDirector\":\"\",\"TechMonitor\":\"\",\"Attemper\":\"\",\"Rationer\":\"\",\"SendTeam\":\"\",\"ManHour\":\"\",\"BeginWorkDate\":\"\",\"EndWorkDate\":\"\",\"F_CertificateId\":\"96a0f9cd-bc52-4d6d-8579-97de4885822e\",\"ExportDate\":null,\"ImportDate\":null}}}";
                        //string qcCardJson = "{ \"code\":200, \"info\":\"响应成功\", \"data\":{ }}";
                        QcCardDto qcCardDto = new QcCardDto();

                        //格式化json成对象数组
                        qcCardDto = JsonConvert.DeserializeObject<QcCardDto>(qcCardJson);
                        if (qcCardDto.data.QcCard != null)
                        {
                            //string materialAllocationJson = PostStoreApp("http://10.19.1.121:31173/learun/adms/qccardapi/GetMaterialAllocation?qcCardCode=" + certificateDto.data.Certificate.QcCardCode, "");
                            string materialAllocationJson = "{ \"code\":200, \"info\":\"响应成功\", \"data\":{ \"MaterialF\":{\"F_MaterialFId\":\"3df72c92-ee60-4f86-8f04-8731270277a2\",\"F_CompanyId\":\"4a31e801-07a8-41e7-bf72-bc4300118bf1\",\"F_DepartmentId\":\"a80eacf6-7365-4814-84ba-066e4487720c\",\"F_CreateDate\":\"2021-09-11 14:34:29\",\"F_CreateUserId\":\"f2c0348b-6fcc-4fa0-9241-ea182dc7a5c3\",\"F_CreateUserName\":\"姜述伟\",\"F_ModifyDate\":null,\"F_ModifyUserId\":null,\"F_ModifyUserName\":null,\"F_SortCode\":1,\"F_DeleteMark\":0,\"F_EnabledMark\":1,\"F_Workshop\":\"51\",\"F_WorkshopName\":\"51车间\",\"AmountF\":1,\"MaterialBillNumF\":\"\",\"BaoGuanQi\":\"\",\"MaterialCerCode\":\"J-DC2108254633-10\",\"FuYanBaoGaoNum\":\"20P2-J404\",\"MaterialChecker\":\"\",\"LuPiHao\":\"N200133\",\"MaterialNumberF\":\"7050\",\"NoMaterialMakeDate\":\"\",\"ProvideStateF\":\"T7451\",\"SpecificationF\":\"20*300*320\",\"TechConditionF\":\"Q/SWA J5020-2009\",\"UnitF\":\"个\",\"ZhouZhuanQi\":\"\",\"ProvideDepartment\":\"Dp\",\"WuZiBianMa\":\"\",\"F_MaterialLId\":\"ee22ef72-fc98-4875-af2a-9b832c173222\",\"F_QcCardId\":\"d19fff19-e063-43ad-ba5c-568becce4938\",\"QcCardCode\":\"5121003033\"}}}";
                            //string materialAllocationJson = "{\"code\":200,\"info\":\"响应成功\",\"data\":{\"MaterialF\":null}}";
                            MaterialAllocationDto materialAllocationDto = new MaterialAllocationDto();
                            //格式化json成对象数组
                            materialAllocationDto = JsonConvert.DeserializeObject<MaterialAllocationDto>(materialAllocationJson);
                            if (materialAllocationDto.data.MaterialF != null)
                            {
                                var unitCodePPtr = _sysCodeRepository.FirstOrDefault(s => s.Description == "单位").Id;
                                var unitCode = _sysCodeRepository.FirstOrDefault(s => s.IsUsed == 1 && s.Description == materialAllocationDto.data.MaterialF.UnitF && s.PPtr == unitCodePPtr);
                                if (unitCode == null && materialAllocationDto.data.MaterialF.UnitF != "" && materialAllocationDto.data.MaterialF.UnitF != null)
                                {
                                    sysCodeDto.Description = materialAllocationDto.data.MaterialF.UnitF;
                                    sysCodeDto.IsUsed = 1;
                                    sysCodeDto.PPtr = _sysCodeRepository.FirstOrDefault(s => s.Description == "单位").Id;
                                    _sysCodeAppServiceRepository.CreateOrUpdateCode(sysCodeDto);
                                    _unitOfWorkManager.Current.SaveChanges();
                                }
                                //炉(批)号
                                storePutModelContentDto.HeatNumber = materialAllocationDto.data.MaterialF.LuPiHao == "" ? null : materialAllocationDto.data.MaterialF.LuPiHao;
                                //化(试)验号
                                storePutModelContentDto.Mthd = materialAllocationDto.data.MaterialF.FuYanBaoGaoNum == "" ? null : materialAllocationDto.data.MaterialF.FuYanBaoGaoNum;
                                //材料牌号
                                storePutModelContentDto.MaterialGrade = materialAllocationDto.data.MaterialF.MaterialNumberF == "" ? null : materialAllocationDto.data.MaterialF.MaterialNumberF;
                                //材料状态
                                storePutModelContentDto.MaterialStatus = materialAllocationDto.data.MaterialF.ProvideStateF == "" ? null : materialAllocationDto.data.MaterialF.ProvideStateF;
                                //技术条件
                                storePutModelContentDto.TechnicalConditions = materialAllocationDto.data.MaterialF.TechConditionF == "" ? null : materialAllocationDto.data.MaterialF.TechConditionF;
                                //材料合格证
                                storePutModelContentDto.MaterialCertificate = materialAllocationDto.data.MaterialF.MaterialCerCode == "" ? null : materialAllocationDto.data.MaterialF.MaterialCerCode;
                                //供应单位
                                storePutModelContentDto.SupplyCompany = materialAllocationDto.data.MaterialF.ProvideDepartment == "" ? null : materialAllocationDto.data.MaterialF.ProvideDepartment;
                                //非金属制造日期
                                if (materialAllocationDto.data.MaterialF.NoMaterialMakeDate != null & materialAllocationDto.data.MaterialF.NoMaterialMakeDate != "")
                                {
                                    storePutModelContentDto.NonMetallicManufacturingDate = Convert.ToDateTime(materialAllocationDto.data.MaterialF.NoMaterialMakeDate);
                                }
                                if (storePutModelContentDto.SuppressionDate == null)
                                {
                                    storePutModelContentDto.MaterialBrandStatus = materialAllocationDto.data.MaterialF.SpecificationF + '/' + materialAllocationDto.data.MaterialF.ProvideStateF + '/' + materialAllocationDto.data.MaterialF.MaterialNumberF;
                                }
                                if (storePutModelContentDto.SuppressionDate != null)
                                {
                                    storePutModelContentDto.NonmetallicMaterialsBrand = materialAllocationDto.data.MaterialF.SpecificationF + '/' + materialAllocationDto.data.MaterialF.ProvideStateF + '/' + materialAllocationDto.data.MaterialF.MaterialNumberF;
                                }
                            }
                            //string[] productModels = qcCardDto.data.QcCard.ProductModel.Split(',');
                            //for (var i = 0; i < (productModels.Length); i++)
                            //{
                            //    var productCodePPtr = _sysCodeRepository.FirstOrDefault(s => s.Description == "型号").Id;
                            //    var productCode = _sysCodeRepository.FirstOrDefault(s => s.IsUsed == 1 && s.Description == productModels[i] && s.PPtr == productCodePPtr);
                            //    if (productCode == null && productModels[i] != "" && productModels[i] != null)
                            //    {
                            //        sysCodeDto.Description = productModels[i];
                            //        sysCodeDto.IsUsed = 1;
                            //        sysCodeDto.PPtr = _sysCodeRepository.FirstOrDefault(s => s.Description == "型号").Id;
                            //        _sysCodeAppServiceRepository.CreateOrUpdateCode(sysCodeDto);
                            //        _unitOfWorkManager.Current.SaveChanges();
                            //    }
                            //}

                            //合格证Id
                            storePutModelContentDto.CertificateId = certificateDto.data.Certificate.F_CertificateId;
                            // 合格证号
                            storePutModelContentDto.QualifiedNumber = certificateDto.data.Certificate.CertificateCode;
                            //产品名称
                            storePutModelContentDto.ProductName = qcCardDto.data.QcCard.ProductName == "" ? null : qcCardDto.data.QcCard.ProductName;
                            //批次
                            if (!string.IsNullOrEmpty(qcCardDto.data.QcCard.ProductBatchNumber)) storePutModelContentDto.Batch = qcCardDto.data.QcCard.ProductBatchNumber;
                            else storePutModelContentDto.Batch = "01";
                            //合格证号任务
                            storePutModelContentDto.QualifiedTaskNumber = qcCardDto.data.QcCard.TaskNumber == "" ? null : qcCardDto.data.QcCard.TaskNumber;
                            //可用数量
                            storePutModelContentDto.Quantity = int.Parse(certificateDto.data.Certificate.UseableAmount);
                            //产品编号(件号)
                            storePutModelContentDto.ProductNumber = certificateDto.data.Certificate.UseableJianNum == "" ? null : certificateDto.data.Certificate.UseableJianNum;
                            //接收车间
                            storePutModelContentDto.InceptWorkshop = certificateDto.data.Certificate.InceptWorkshop == "" ? null : certificateDto.data.Certificate.InceptWorkshop;
                            //特殊记载
                            storePutModelContentDto.SpecialRecords = certificateDto.data.Certificate.Remark == "" ? null : certificateDto.data.Certificate.Remark;
                            //批次号
                            storePutModelContentDto.BatchNo = qcCardDto.data.QcCard.BatchNum == "" ? null : qcCardDto.data.QcCard.BatchNum;
                            //压制日期=非金属压制日期
                            storePutModelContentDto.SuppressionDate = qcCardDto.data.QcCard.NonmetalDate == "" ? null : qcCardDto.data.QcCard.NonmetalDate;
                            //处理技术问题文件编号(技术文件号)
                            storePutModelContentDto.DocumentNo = certificateDto.data.Certificate.TechFileCode == "" ? null : certificateDto.data.Certificate.TechFileCode;
                            //制造车间
                            storePutModelContentDto.ManufacturingWorkshop = qcCardDto.data.QcCard.MainWorkshop == "" ? null : qcCardDto.data.QcCard.MainWorkshop;
                            //生产工人
                            storePutModelContentDto.ProductionWorkers = qcCardDto.data.QcCard.ProducePerson == "" ? null : qcCardDto.data.QcCard.ProducePerson;
                            //工(组)长
                            storePutModelContentDto.Foreman = qcCardDto.data.QcCard.SectionChief == "" ? null : qcCardDto.data.QcCard.SectionChief;
                            //检验员
                            storePutModelContentDto.Inspector = certificateDto.data.Certificate.KaiZhengPerson == "" ? null : certificateDto.data.Certificate.KaiZhengPerson;
                            //开证日期
                            storePutModelContentDto.Date = certificateDto.data.Certificate.KaiZhengDate == "" ? null : certificateDto.data.Certificate.KaiZhengDate;
                            //质控卡号
                            storePutModelContentDto.QCCardNo = certificateDto.data.Certificate.QcCardCode == "" ? null : certificateDto.data.Certificate.QcCardCode;
                            //阶段标记
                            storePutModelContentDto.StageMark = qcCardDto.data.QcCard.PhaseSign == "" ? null : qcCardDto.data.QcCard.PhaseSign;
                            //协作合格证
                            storePutModelContentDto.CooperationCertificate = certificateDto.data.Certificate.XzCertificatCode == "" ? null : certificateDto.data.Certificate.XzCertificatCode;
                            //非金属压制日期 = 压制日期
                            if (storePutModelContentDto.SuppressionDate != null)
                            {
                                storePutModelContentDto.NonMetallicPressingDate = Convert.ToDateTime(qcCardDto.data.QcCard.NonmetalDate);
                            }
                            StandardOutputDto standardOutputDto = _storeFunctionsAppServicepository.GetStandardDrawingNoDispose(qcCardDto.data.QcCard.DrawingNumber);
                            storePutModelContentDto.ProductModel = qcCardDto.data.QcCard.ProductModel;
                            //型号(产品代号) 发次
                            if (!string.IsNullOrEmpty(qcCardDto.data.QcCard.ProductModel))
                            {

                                if (qcCardDto.data.QcCard.ProductModel != "标准件")
                                {
                                    var productCodeList = from sc in _sysCodeRepository.GetAll().Where(s => s.IsUsed == 1)
                                                          join scc in _sysCodeRepository.GetAll()
                                                          on sc.PPtr equals scc.Id
                                                          where scc.Description == "型号"
                                                          select sc;
                                    //var product = productCodeList.FirstOrDefault(s => s.Description == qcCardDto.ProductModel);
                                    string[] productModels = qcCardDto.data.QcCard.ProductModel.Split(',');
                                    for (var i = 0; i < (productModels.Length); i++)
                                    {
                                        var productCodePPtr = _sysCodeRepository.FirstOrDefault(s => s.Description == "型号").Id;
                                        var productCode = _sysCodeRepository.FirstOrDefault(s => s.IsUsed == 1 && s.Description == productModels[i] && s.PPtr == productCodePPtr);
                                        if (productCode == null && productModels[i] != "" && productModels[i] != null)
                                        {
                                            throw new UserFriendlyException("型号里没有" + productModels[i] + ",请在数据字典里添加该型号再入库");
                                        }
                                    }
                                    storePutModelContentDto.ProductCode = string.Join(",", productCodeList.Where(s => qcCardDto.data.QcCard.ProductModel.Contains(s.Description)).Select(s => s.Id.ToString().ToUpper()));
                                    storePutModelContentDto.ProductCodeName = qcCardDto.data.QcCard.ProductModel;
                                    var index = qcCardDto.data.QcCard.ProductModel.IndexOf("系列");
                                    if (index > 0)
                                    {
                                        storePutModelContentDto.SendTimeName = "全发次";
                                        var st = _sysCodeRepository.FirstOrDefault(s => s.Description == "全发次");
                                        if (st != null)
                                        {
                                            storePutModelContentDto.SendTime = st.Id.ToString().ToUpper();
                                        }
                                    }
                                }
                                else
                                {
                                    var makeTask = _makeTaskRepository.FirstOrDefault(s => s.JobNumber == storePutModelContentDto.QualifiedTaskNumber);
                                    if (makeTask != null)
                                    {
                                        storePutModelContentDto.ProductCode = makeTask.ModelId.ToString().ToUpper();
                                        storePutModelContentDto.ProductCodeName = _sysCodeRepository.FirstOrDefault(s => s.Id == makeTask.ModelId).Description;
                                        storePutModelContentDto.SendTime = makeTask.LotNoId.ToString().ToUpper();
                                        storePutModelContentDto.SendTimeName = _sysCodeRepository.FirstOrDefault(s => s.Id == makeTask.LotNoId).Description;
                                    }
                                }
                            }
                            var module = "-";
                            if (string.IsNullOrEmpty(standardOutputDto.Module))
                            {
                                if (!string.IsNullOrEmpty(certificateDto.data.Certificate.CerSpecParam))
                                {
                                    module = certificateDto.data.Certificate.CerSpecParam.ToUpper();
                                }
                            }
                            else
                            {
                                module = standardOutputDto.Module;
                            }
                            if (!string.IsNullOrEmpty(standardOutputDto.YearNo)) storePutModelContentDto.ProductDrawingNo = standardOutputDto.ProductDrawingNo + "-" + standardOutputDto.YearNo;
                            else storePutModelContentDto.ProductDrawingNo = standardOutputDto.ProductDrawingNo;
                            //材料规格
                            storePutModelContentDto.MaterialSpecification = module;
                            //标准件规格=材料规格，同一字段
                            storePutModelContentDto.StandardSpecification = module;
                            //规格 =材料规格
                            storePutModelContentDto.Module = module;
                            //物料、类别细类、单位
                            var materialsContent = _materialsContentRepository.FirstOrDefault(s => s.MaterialNo == standardOutputDto.ProductDrawingNo && s.Model == storePutModelContentDto.Module);
                            if (materialsContent != null)
                            {
                                storePutModelContentDto.MaterialCategoryId = materialsContent.MaterialsNodeId;
                                storePutModelContentDto.MaterialsNodeId = materialsContent.MaterialsNodeId;
                                storePutModelContentDto.UnitId = materialsContent.UnitId;
                            }
                            else if (materialsContent == null && standardOutputDto.IsStandar == 1)
                            {
                                var standarNo = _materialsNodeRepository.FirstOrDefault(s => s.MaterialTypeName == "标准件");
                                storePutModelContentDto.MaterialCategoryId = standarNo.Id;
                                storePutModelContentDto.MaterialsNodeId = standarNo.Id;
                            }
                            if (storePutModelContentDto.UnitId == null)
                            {
                                if (!string.IsNullOrEmpty(materialAllocationDto.data.MaterialF.UnitF))
                                {
                                    var unitCodeList = from sc in _sysCodeRepository.GetAll().Where(s => s.IsUsed == 1)
                                                       join scc in _sysCodeRepository.GetAll()
                                                       on sc.PPtr equals scc.Id
                                                       where scc.Description == "单位"
                                                       select sc;
                                    var unit = unitCodeList.FirstOrDefault(s => s.Description == materialAllocationDto.data.MaterialF.UnitF);
                                    if (unit != null)
                                    {
                                        storePutModelContentDto.UnitId = unit.Id;
                                    }
                                }
                            }
                            //所有产品编码（增加字段：是否可用）
                            storePutModelContentDto.JianNum = certificateDto.data.Certificate.JianNum == "" ? null : certificateDto.data.Certificate.JianNum;
                            //数量
                            storePutModelContentDto.Amount = int.Parse(certificateDto.data.Certificate.Amount);
                            return storePutModelContentDto;
                        }
                        else
                        {
                            throw new UserFriendlyException("没有查询到该合格证的质控卡信息");
                        }
                    }
                    else
                    {
                        throw new UserFriendlyException("没有查询到该合格证号");
                    }
                }
                catch (Exception ex)
                {
                    throw new UserFriendlyException(ex.Message);
                }
            }
            else
            {
                throw new UserFriendlyException("请输入有效的合格证号");
            }
        }
        /// <summary>
        /// 查询主表格数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<StorePutModelContentDto>> GetParentPutStoreGrid(GetStoreContenListDto input)
        {
            var storePutRecord = _storePutRecordRepository.GetAll();
            var queryStorePutContents = from spr in storePutRecord
                                        from spc in _storePutContentRepository.GetAll()
                                        where spr.QualifiedNumber == spc.QualifiedNumber && spr.ReleaseOrder == spc.ReleaseOrder
                                        select new
                                        {
                                            Id = spc.Id,
                                            StorePutRecordId = spr.Id,
                                            StorePutNo = spc.StorePutNo,
                                            StoreId = spc.StoreId,
                                            StroeName = spc.StroeName,
                                            BinLocationId = spc.BinLocationId,
                                            BinLocation = spc.BinLocation,
                                            MaterialsContentId = spc.MaterialsContentId,
                                            ReleaseOrder = spr.ReleaseOrder,
                                            Remark = spc.Remark,
                                            StoreStateContent = spc.StoreStateContent,
                                            StorePutPeopleId = spr.StorePutPeopleId,
                                            StorePutTime = spr.StorePutTime,
                                            IdentifyingPeopleId = spc.IdentifyingPeopleId,
                                            IdentifyingTime = spc.IdentifyingTime,
                                            QualifiedNumber = spr.QualifiedNumber,
                                            ProductDrawingNo = spc.ProductDrawingNo,
                                            ProductName = spc.ProductName,
                                            Batch = spc.Batch,
                                            QualifiedTaskNumber = spc.QualifiedTaskNumber,
                                            Quantity = spr.Quantity,
                                            ProductNumber = spr.ProductNumber,
                                            ProductNumberShow = spc.ProductNumberShow,
                                            ProductNumberType = spc.ProductNumberType,
                                            SpecialRecords = spr.SpecialRecords,
                                            MaterialBrandStatus = spc.MaterialBrandStatus,
                                            HeatNumber = spc.HeatNumber,
                                            Mthd = spc.Mthd,
                                            NonmetallicMaterialsBrand = spc.NonmetallicMaterialsBrand,
                                            BatchNo = spc.BatchNo,
                                            SuppressionDate = spc.SuppressionDate,
                                            DocumentNo = spc.DocumentNo,
                                            ManufacturingWorkshop = spc.ManufacturingWorkshop,
                                            ProductionWorkers = spc.ProductionWorkers,
                                            Foreman = spc.Foreman,
                                            Inspector = spc.Inspector,
                                            Date = spc.Date,
                                            QCCardNo = spr.QCCardNo,
                                            AssemblyTaskNumber = spc.AssemblyTaskNumber,
                                            StageMark = spc.StageMark,
                                            MaterialGrade = spc.MaterialGrade,
                                            MaterialStatus = spc.MaterialStatus,
                                            MaterialSpecification = spc.Module,
                                            StandardSpecification = spc.Module,
                                            TechnicalConditions = spc.TechnicalConditions,
                                            MaterialCertificate = spc.MaterialCertificate,
                                            CooperationCertificate = spc.CooperationCertificate,
                                            SupplyCompany = spc.SupplyCompany,
                                            NonMetallicManufacturingDate = spc.NonMetallicManufacturingDate,
                                            NonMetallicPressingDate = spc.NonMetallicPressingDate,
                                            ProductCode = spc.ProductCode,
                                            ProductCodeId = spc.ProductCodeId,
                                            SendTime = spc.SendTime,
                                            SendTimeId = spc.SendTimeId,
                                            Module = spc.Module,
                                            ExpirationDate = spc.ExpirationDate == "2099-01-01T00:00:00.000Z" ? null : spc.ExpirationDate,
                                            UnitId = spc.UnitId,
                                            Unit = spc.Unit,
                                            TurnBatch = spc.TurnBatch,
                                            MaterialsProperty = spr.MaterialsProperty,
                                            WarehousMethod = spc.WarehousMethod,
                                            IsolationCode = spc.IsolationCode,
                                            IsolationReason = spc.IsolationReason,
                                            IsolationUserId = spc.IsolationUserId,
                                            IsolationUser = spc.IsolationUser,
                                            IsolationTime = spc.IsolationTime,
                                            CreatorUserId = spr.CreatorUserId,
                                            CreationTime = spr.CreationTime,
                                        };
            if (queryStorePutContents.Count() > 0)
            {
                var userTemp = _userRepository.GetAll().ToList();
                queryStorePutContents = queryStorePutContents.WhereIf(input.StoreId != Guid.Empty, d => d.StoreId == input.StoreId)
                    .WhereIf(!string.IsNullOrEmpty(input.StorePutNo), d => d.StorePutNo == input.StorePutNo)
                    .WhereIf(!string.IsNullOrEmpty(input.ProductDrawingNo), d => d.ProductDrawingNo.Contains(input.ProductDrawingNo))
                    .WhereIf(!string.IsNullOrEmpty(input.QualifiedNumber), d => d.QualifiedNumber == input.QualifiedNumber)
                    .WhereIf(!string.IsNullOrEmpty(input.TaskNumber), d => d.QualifiedTaskNumber == input.TaskNumber)
                    .WhereIf(!string.IsNullOrEmpty(input.BinLocationId), d => d.BinLocationId == input.BinLocationId);
                if (!string.IsNullOrEmpty(input.PutStoreUser))
                {
                    queryStorePutContents = from qspc in queryStorePutContents
                                            join ur in userTemp
                                            on qspc.CreatorUserId equals ur.Id
                                            where ur.Surname + ur.Name == input.PutStoreUser
                                            select qspc;
                }
                if (input.Sorting.ToLower() == "storestatecontent asc")
                {
                    queryStorePutContents = queryStorePutContents.OrderBy(s => s.StoreStateContent).ThenBy(s => s.CreationTime).PageBy(input);
                }
                else if (input.Sorting.ToLower() == "storestatecontent desc")
                {
                    queryStorePutContents = queryStorePutContents.OrderByDescending(s => s.StoreStateContent).ThenBy(s => s.CreationTime).PageBy(input);
                }
                else
                {
                    queryStorePutContents = queryStorePutContents.OrderByDescending(s => s.CreationTime).PageBy(input);
                }
                var materialsNode = _materialsNodeRepository.GetAll();
                List<StorePutModelContentDto> storePuts = new List<StorePutModelContentDto>();
                var query = queryStorePutContents.ToList();
                for (int i = 0; i < queryStorePutContents.Count(); i++)
                {
                    //var query = queryStorePutContents.ToList();
                    var materialsContents = _materialsContentRepository.FirstOrDefault(s => s.Id == query[i].MaterialsContentId);
                    if (materialsContents != null)
                    {
                        var storeStockContent = _storeStockContentRepository.GetAll().Where(s => s.StorePutContentId == query[i].Id);
                        StorePutModelContentDto storePut = new StorePutModelContentDto();
                        storePut.ProductCodeName = query[i].ProductCode;
                        storePut.ProductCode = query[i].ProductCodeId;
                        storePut.SendTimeName = query[i].SendTime;
                        storePut.SendTime = query[i].SendTimeId;
                        storePut.Id = query[i].Id;
                        storePut.StorePutRecordId = query[i].StorePutRecordId;
                        storePut.CreationTime = query[i].CreationTime;
                        storePut.CreatorUserId = query[i].CreatorUserId;
                        storePut.StorePutNo = query[i].StorePutNo;
                        storePut.StoreId = query[i].StoreId;
                        storePut.StroeName = query[i].StroeName;
                        storePut.BinLocationId = query[i].BinLocationId;
                        storePut.BinLocation = query[i].BinLocation;
                        storePut.MaterialsContentId = query[i].MaterialsContentId;
                        storePut.ReleaseOrder = query[i].ReleaseOrder;
                        storePut.Remark = query[i].Remark;
                        storePut.StorePutPeople = userTemp.FirstOrDefault(d => d.Id == query[i].CreatorUserId).Surname + userTemp.FirstOrDefault(d => d.Id == query[i].CreatorUserId).Name;
                        storePut.StoreStateContent = (int)query[i].StoreStateContent;
                        storePut.StorePutTime = query[i].StorePutTime;
                        storePut.IdentifyingPeopleId = query[i].IdentifyingPeopleId;
                        if (query[i].IdentifyingPeopleId != null)
                        {
                            storePut.IdentifyingPeople = userTemp.FirstOrDefault(d => d.Id == query[i].IdentifyingPeopleId).Surname + userTemp.FirstOrDefault(d => d.Id == query[i].IdentifyingPeopleId).Name;
                        }
                        storePut.IdentifyingTime = query[i].IdentifyingTime;
                        //合格证号
                        storePut.QualifiedNumber = query[i].QualifiedNumber;
                        //产品图号
                        storePut.ProductDrawingNo = query[i].ProductDrawingNo;
                        //产品名称
                        storePut.ProductName = query[i].ProductName;
                        //批次
                        storePut.Batch = query[i].Batch;
                        //合格证号任务
                        storePut.QualifiedTaskNumber = query[i].QualifiedTaskNumber;
                        //数量
                        storePut.Quantity = query[i].Quantity;
                        //产品编号(件号)
                        storePut.ProductNumber = query[i].ProductNumber;
                        //产品编号(用于修改)
                        storePut.ProductNumberShow = query[i].ProductNumberShow;
                        //产品编号生成方式 0：自动带出，1：手动输入， 3：自动生成
                        storePut.ProductNumberType = (int)query[i].ProductNumberType;
                        //特殊记载
                        storePut.SpecialRecords = query[i].SpecialRecords;
                        //金属材料牌号状态
                        storePut.MaterialBrandStatus = query[i].MaterialBrandStatus;
                        //炉(批)号
                        storePut.HeatNumber = query[i].HeatNumber;
                        //化(试)验号
                        storePut.Mthd = query[i].Mthd;
                        //非金属材料牌号
                        storePut.NonmetallicMaterialsBrand = query[i].NonmetallicMaterialsBrand;
                        //批次号
                        storePut.BatchNo = query[i].BatchNo;
                        //压制日期
                        storePut.SuppressionDate = query[i].SuppressionDate;
                        //处理技术问题文件编号
                        storePut.DocumentNo = query[i].DocumentNo;
                        //制造车间
                        storePut.ManufacturingWorkshop = query[i].ManufacturingWorkshop;
                        //生产工人
                        storePut.ProductionWorkers = query[i].ProductionWorkers;
                        //工(组)长
                        storePut.Foreman = query[i].Foreman;
                        //检验员
                        storePut.Inspector = query[i].Inspector;
                        //日期
                        storePut.Date = query[i].Date;
                        //质控卡号
                        storePut.QCCardNo = query[i].QCCardNo;
                        //装配任务号
                        storePut.AssemblyTaskNumber = query[i].AssemblyTaskNumber;
                        //阶段标记
                        storePut.StageMark = query[i].StageMark;
                        //材料牌号
                        storePut.MaterialGrade = query[i].MaterialGrade;
                        //材料状态
                        storePut.MaterialStatus = query[i].MaterialStatus;
                        //材料规格
                        storePut.MaterialSpecification = query[i].MaterialSpecification;
                        //标准件规格
                        storePut.StandardSpecification = query[i].StandardSpecification;
                        //技术条件
                        storePut.TechnicalConditions = query[i].TechnicalConditions;
                        //材料合格证
                        storePut.MaterialCertificate = query[i].MaterialCertificate;
                        //协作合格证
                        storePut.CooperationCertificate = query[i].CooperationCertificate;
                        //供应单位
                        storePut.SupplyCompany = query[i].SupplyCompany;
                        //非金属制造日期
                        storePut.NonMetallicManufacturingDate = query[i].NonMetallicManufacturingDate;
                        //非金属压制日期
                        storePut.NonMetallicPressingDate = query[i].NonMetallicPressingDate;

                        ////型号(产品代号)
                        //storePut.ProductCode = query[i].ProductCodeId;
                        ////发次
                        //storePut.SendTime = query[i].SendTimeId;
                        //物料细分类别
                        storePut.MaterialCategoryId = materialsContents.MaterialCategoryId;
                        storePut.MaterialCategory = _materialsNodeRepository.FirstOrDefault(s => s.Id == materialsContents.MaterialCategoryId).MaterialTypeName;
                        //物料类别(有问题)
                        storePut.MaterialsNodeId = materialsContents.MaterialsNodeId;
                        storePut.MaterialsNode = _materialsNodeRepository.FirstOrDefault(s => s.Id == materialsContents.MaterialsNodeId).MaterialTypeName;
                        //规格型号
                        storePut.Module = query[i].Module;
                        //有效期止
                        storePut.ExpirationDate = query[i].ExpirationDate == "2099-01-01T00:00:00.000Z" ? null : query[i].ExpirationDate;
                        //单位Id
                        storePut.UnitId = query[i].UnitId;
                        //单位
                        storePut.Unit = query[i].Unit;
                        //转批次
                        storePut.TurnBatch = query[i].TurnBatch;
                        //物料属性
                        storePut.MaterialsProperty = (int)query[i].MaterialsProperty;
                        ////入库状态
                        //storePut.InputState = (int)query[i].InputState;
                        //入库方式
                        storePut.WarehousMethod = (int)query[i].WarehousMethod;
                        storePuts.Add(storePut);
                    }
                }
                var count = storePuts.Count();
                return new PagedResultDto<StorePutModelContentDto>(count, storePuts);
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 查询物料建模，若没有对应的类别，细类，详细信息，就增加。
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<StoreReturnIdDto> CreateMaterialsContentByStore(StorePutModelContentDto input)
        {
            var materialsNode = _materialsNodeRepository.GetAll();
            var materialsContent = _materialsContentRepository.GetAll();
            var node = materialsNode.FirstOrDefault(s => s.Id == input.MaterialsNodeId && s.LevelNum == 1);
            StoreReturnIdDto storeReturnIdDto = new StoreReturnIdDto();
            var nodeCategory = materialsNode.FirstOrDefault(s => s.Id == input.MaterialCategoryId && (s.LevelNum == 1 || s.LevelNum == 2));
            var productDrawingNo = input.ProductDrawingNo;
            var materialType = _materialsNodeRepository.FirstOrDefault(d => d.Id == input.MaterialsNodeId);
            if (productDrawingNo.IndexOf("-") >= 0 && materialType.MaterialTypeName == "标准件")
            {
                productDrawingNo = input.ProductDrawingNo.Substring(0, input.ProductDrawingNo.LastIndexOf("-"));
            }
            MaterialsEditContentDto materialsEditContentDto = new MaterialsEditContentDto();
            {
                //物料代码
                materialsEditContentDto.MaterialNo = productDrawingNo;
                //物料名称
                materialsEditContentDto.MaterialName = input.ProductName;
                //规格型号
                materialsEditContentDto.Model = input.Module;
                //类型id
                materialsEditContentDto.MaterialsNodeId = node.Id;
                //单位
                materialsEditContentDto.UnitId = (Guid)input.UnitId;
                //是否使用 1：使用
                materialsEditContentDto.IsUsed = 1;
                //是否关键件 1：是
                materialsEditContentDto.IsKeyPart = 1;
                //是否标准件 1：是
                materialsEditContentDto.IsStandard = 1;
                //备注
                materialsEditContentDto.Remark = input.Remark;
                ////图号
                //materialsEditContentDto.DrawingNo = input.ProductDrawingNo;
                ////发次
                //materialsEditContentDto.SendTime = materialsEditContentDto.SendTime;
                //物料类别组合编码
                materialsEditContentDto.MaterialTypeCode = nodeCategory.MaterialsTypeCode;
                //物料属性 字段待讨论
                materialsEditContentDto.MaterialProperty = 3;
                //物料细分类别
                materialsEditContentDto.MaterialCategoryId = nodeCategory.Id;
                //批次
                materialsEditContentDto.Batch = input.Batch;
            }
            storeReturnIdDto = await _materialsAppServiceRepository.CreateOrUpdateMaterialsContent(materialsEditContentDto);
            //        }

            //    }
            //}
            return storeReturnIdDto;
        }
        /// <summary>
        /// 保存合格证入库信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultMessage> CreateStorePutContent(List<StorePutModelContentDto> input, Guid codeFormatId)
        {
            ResultMessage result = new ResultMessage();
            try
            {
                if (input.Count() == 0)
                {
                    result.code = 1;
                    result.Message = "请填写数据后再入库";
                    return result;
                }
                foreach (StorePutModelContentDto spc in input)
                {
                    #region 必填项去除前后空格并判断null值
                    //放行单重复检查
                    if (spc.WarehousMethod == 1)
                    {
                        spc.ReleaseOrder = spc.ReleaseOrder.Trim();
                        if (spc.ReleaseOrder == null)
                        {
                            result.code = 1;
                            result.Message = "放行单号不能填空格";
                            return result;
                        }
                        var releaseOrder = _storePutContentRepository.FirstOrDefaultAsync(s => s.ReleaseOrder == spc.ReleaseOrder).Result;
                        if (releaseOrder != null)
                        {
                            result.code = 1;
                            result.Message = "放行单号不能重复";
                            return result;
                        }
                    }
                    if (spc.WarehousMethod == 0 || spc.WarehousMethod == 2)
                    {
                        spc.QualifiedNumber = spc.QualifiedNumber.Trim();
                        if (spc.QualifiedNumber == null)
                        {
                            result.code = 1;
                            result.Message = "合格证号不能填空格";
                            return result;
                        }
                    }
                    spc.ProductDrawingNo = spc.ProductDrawingNo.Trim();
                    if (spc.ProductDrawingNo == null)
                    {
                        result.code = 1;
                        result.Message = "产品图号不能填空格";
                        return result;
                    }
                    spc.ProductDrawingNo = spc.ProductDrawingNo.ToUpper();
                    spc.ProductName = spc.ProductName.Trim();
                    if (spc.ProductName == null)
                    {
                        result.code = 1;
                        result.Message = "产品名称不能填空格";
                        return result;
                    }
                    spc.Batch = spc.Batch.Trim();
                    if (spc.Batch == null)
                    {
                        result.code = 1;
                        result.Message = "批次不能填空格";
                        return result;
                    }
                    spc.Module = spc.Module.Trim();
                    if (spc.Module == null)
                    {
                        result.code = 1;
                        result.Message = "规格不能填空格";
                        return result;
                    }
                    spc.Module = spc.Module.Replace("X", "x").Replace("*", "x").Replace("×", "x").ToUpper();
                    #endregion
                    //if (spc.Module == null)
                    //{
                    //    result.code = 1;
                    //    result.Message = "请填写产品图号、产品名称、规格";
                    //    return result;
                    //}
                    List<string> productNumberList = new List<string>();
                    List<string> productNumberShowList = new List<string>();
                    var count = 0;
                    if (spc.ProductNumber != null)
                    {
                        string[] productNumber = spc.ProductNumber.Replace("，", ",").Split(",").ToList().Where(d => !string.IsNullOrEmpty(d) && d != "undefined" && d != "").ToArray();
                        count = spc.ProductNumber.Split(",").Length;
                        productNumberShowList = new List<string>(productNumber);

                        productNumberList = new List<string>(productNumber);
                        for (int i = 0; i < spc.Quantity - productNumber.Length; i++)
                        {
                            productNumberList.Add("undefined");
                        }
                    }
                    else
                    {
                        for (int i = 0; i < spc.Quantity; i++)
                        {
                            productNumberList.Add("undefined");
                        }
                    }
                    if (spc.Quantity == 0 || spc.Quantity < count)
                    {
                        result.code = 1;
                        result.Message = "合格证上的数量不能为0或者比产品编号的个数少";
                        return result;
                    }
                    List<string> sendTime = new List<string>(spc.SendTime.Split(',').ToArray());
                    List<string> productCode = new List<string>(spc.ProductCode.Split(',').ToArray());
                    #region 校验数据仓库中和物料信息中是否存在(根据图号、规格 判断物料详细表中是否存在，如果不存在就新增，否则仓库信息表中新增 状态为待入库)
                    var queryStoreContent = _storePutContentRepository.FirstOrDefaultAsync(t => t.QualifiedNumber == spc.QualifiedNumber && spc.QualifiedNumber != null).Result;
                    var productDrawingNo = spc.ProductDrawingNo;
                    var materialType = _materialsNodeRepository.FirstOrDefault(d => d.Id == spc.MaterialsNodeId);
                    if (productDrawingNo.IndexOf("-") >= 0 && materialType.MaterialTypeName == "标准件")
                    {
                        #region 年代号校验
                        var year = spc.ProductDrawingNo.Substring(spc.ProductDrawingNo.LastIndexOf("-") + 1);
                        if (!string.IsNullOrEmpty(year))
                        {
                            int yearCount = year.Length;
                            if (yearCount == 2 || yearCount == 4)
                            {
                                try
                                {
                                    int.Parse(year);
                                }
                                catch
                                {
                                    result.code = 1;
                                    result.Message = "图号-年代号不正确";
                                    return result;
                                }
                            }
                            else
                            {
                                result.code = 1;
                                result.Message = "图号-年代号不正确";
                                return result;
                            }
                        }
                        #endregion
                        productDrawingNo = spc.ProductDrawingNo.Substring(0, spc.ProductDrawingNo.LastIndexOf("-"));
                    }
                    var queryMaterialsContents = _materialsContentRepository.FirstOrDefaultAsync(t => t.MaterialNo == productDrawingNo && t.Model == spc.Module).Result;
                    if (queryMaterialsContents != null)
                    {
                        if (queryMaterialsContents.IsUsed == 0)
                        {
                            result.code = 1;
                            result.Message = "该物料已经停用";
                            return result;
                        }
                    }
                    StoreReturnIdDto storeReturnIdDto = new StoreReturnIdDto();
                    if (queryMaterialsContents != null)
                    {
                        var nodeName = _materialsNodeRepository.FirstOrDefault(s => s.Id == queryMaterialsContents.MaterialsNodeId).MaterialTypeName;
                        var categoryName = _materialsNodeRepository.FirstOrDefault(s => s.Id == queryMaterialsContents.MaterialCategoryId).MaterialTypeName;
                        if (nodeName != spc.MaterialsNode && categoryName != spc.MaterialCategory)
                        {
                            result.code = 1;
                            result.Message = "物料分类、细类与物料详细信息不符；物料分类：" + nodeName + "，物料细类：" + categoryName;
                            return result;
                        }
                        storeReturnIdDto.MaterialsContentId = queryMaterialsContents.Id;
                    }
                    if (queryStoreContent != null && spc.MaterialsProperty == 0)
                    {
                        result.code = 1;
                        result.Message = "合格证号不能重复";
                        return result;
                    }
                    //返修回来的产品，若用新的合格证号，正常入库，如若用旧的合格证号，物料信息不变，改变原属性入库即可
                    if (queryStoreContent != null && spc.MaterialsProperty == 1)
                    {
                        if (queryMaterialsContents == null)
                        {
                            storeReturnIdDto = await CreateMaterialsContentByStore(spc);
                        }
                        //特殊记载
                        queryStoreContent.SpecialRecords = spc.SpecialRecords;
                        queryStoreContent.MaterialsProperty = MaterialsPropertys.返修正常品;
                        //入库时间
                        queryStoreContent.StorePutTime = DateTime.Now;
                        //型号(产品代号)
                        queryStoreContent.ProductCode = string.Join(",", _sysCodeRepository.GetAll().Where(s => productCode.Contains(s.Id.ToString())).Select(s => s.Description));
                        //型号(产品代号)ID
                        queryStoreContent.ProductCodeId = spc.ProductCode;
                        //发次
                        queryStoreContent.SendTime = string.Join(",", _sysCodeRepository.GetAll().Where(s => sendTime.Contains(s.Id.ToString())).Select(s => s.Description));
                        //发次ID
                        queryStoreContent.SendTimeId = spc.SendTime;
                        //规格型号
                        queryStoreContent.Module = spc.Module;
                        //有效期止
                        queryStoreContent.ExpirationDate = spc.ExpirationDate ?? "2099-01-01T00:00:00.000Z";
                        //单位Id
                        queryStoreContent.UnitId = (Guid)spc.UnitId;
                        //单位
                        queryStoreContent.Unit = spc.Unit;
                        //转批次
                        queryStoreContent.TurnBatch = spc.TurnBatch;
                        // 库存量
                        queryStoreContent.Amount = spc.Amount;
                        // 所有产品编码
                        queryStoreContent.JianNum = spc.JianNum;

                        await _storePutContentRepository.UpdateAsync(queryStoreContent);

                        var storeStockContentList = _storeStockContentRepository.GetAll().Where(s => s.StorePutContentId == queryStoreContent.Id).ToList();
                        _iOperationHistoryAppService.InsertOperationLogNew(queryStoreContent.Id, BusinessTypes.仓库管理, OperationTypes.仓库修改物料, spc.ProductName + "增加返修品信息");
                        //_iOperationHistoryAppService.InsertOperationLog(queryStoreContent.Id, 6, 20, spc.ProductName + "增加返修品信息");
                        result.code = 0;
                        return result;
                    }
                    //查询物料建模，若没有对应的类别，细类，详细信息，就增加。
                    if (queryMaterialsContents == null)
                    {
                        storeReturnIdDto = await CreateMaterialsContentByStore(spc);
                    }
                    #endregion
                    #region  添加仓库物料信息
                    var userId = GetCurrentUser().Id; //add 11/30
                    if (spc.WarehousMethod == 2)
                    {
                        if (spc.NonMetallicPressingDate == null)
                        {
                            spc.MaterialBrandStatus = spc.MaterialGrade + "/" + spc.MaterialStatus + "/" + spc.MaterialSpecification;
                        }
                        else
                        {
                            spc.NonmetallicMaterialsBrand = spc.MaterialGrade + "/" + spc.MaterialStatus + "/" + spc.MaterialSpecification;
                        }
                    }
                    var storePutNo = _codeFormatDescAppServiceRepository.GetCodeFormat("入库管理");
                    if (storePutNo == null)
                    {
                        storePutNo = _codeFormatDescAppServiceRepository.GetOrderCode("RK", "yyyyMMdd", 1, 5, 1);
                    }
                    _unitOfWorkManager.Current.SaveChanges();
                    StorePutModelContentDto storePut = new StorePutModelContentDto();
                    StorePutContent storePutContent = new StorePutContent
                    {
                        #region 入库信息  
                        Id = Guid.NewGuid(),
                        //入库单号
                        StorePutNo = storePutNo,
                        //仓库Id(默认取第一条数据的仓库ID)
                        StoreId = spc.StoreId,
                        //仓库名称(默认取第一条数据的仓库名)
                        StroeName = spc.StroeName,
                        // 储位ID
                        BinLocationId = spc.BinLocationId,
                        // 储位
                        BinLocation = spc.BinLocation,
                        //物料细料ID
                        MaterialsContentId = (Guid)storeReturnIdDto.MaterialsContentId,
                        //放行单号
                        ReleaseOrder = spc.ReleaseOrder,
                        //备注
                        Remark = spc.Remark,
                        //物料入库状态 0待入库、1已入库
                        StoreStateContent = StoreState.待入库,
                        //入库人Id
                        StorePutPeopleId = userId,
                        //入库时间
                        StorePutTime = DateTime.Now,
                        #endregion
                        #region 合格证信息 
                        //合格证Id
                        CertificateId = spc.CertificateId,
                        //合格证号
                        QualifiedNumber = spc.QualifiedNumber,
                        //产品图号
                        ProductDrawingNo = spc.ProductDrawingNo,
                        //产品名称
                        ProductName = spc.ProductName,
                        //批次
                        Batch = spc.Batch,
                        //合格证号任务
                        QualifiedTaskNumber = spc.QualifiedTaskNumber,
                        //数量
                        Quantity = spc.Quantity,
                        //产品编号(件号)
                        ProductNumber = string.Join(",", productNumberList.ToArray()),
                        ProductNumberShow = string.Join(",", productNumberShowList.ToArray()),
                        //产品编号生成方式 0：自动带出，1：手动输入， 3：自动生成
                        ProductNumberType = (StorePutContent.ProductNumberTypes)spc.ProductNumberType,
                        //特殊记载
                        SpecialRecords = spc.SpecialRecords,
                        //金属材料牌号状态
                        MaterialBrandStatus = spc.MaterialBrandStatus,
                        //非金属材料牌号
                        NonmetallicMaterialsBrand = spc.NonmetallicMaterialsBrand,
                        //炉(批)号
                        HeatNumber = spc.HeatNumber,
                        //化(试)验号
                        Mthd = spc.Mthd,
                        //批次号
                        BatchNo = spc.BatchNo,
                        //压制日期
                        SuppressionDate = spc.SuppressionDate,
                        //处理技术问题文件编号
                        DocumentNo = spc.DocumentNo,
                        //制造车间
                        ManufacturingWorkshop = spc.ManufacturingWorkshop,
                        //生产工人
                        ProductionWorkers = spc.ProductionWorkers,
                        //工(组)长
                        Foreman = spc.Foreman,
                        //检验员
                        Inspector = spc.Inspector,
                        //日期
                        Date = spc.Date,
                        //质控卡号
                        QCCardNo = spc.QCCardNo,
                        //装配任务号
                        AssemblyTaskNumber = spc.AssemblyTaskNumber,
                        //阶段标记
                        StageMark = spc.StageMark,
                        //材料牌号
                        MaterialGrade = spc.MaterialGrade,
                        //材料状态
                        MaterialStatus = spc.MaterialStatus,
                        ////材料规格
                        //MaterialSpecification = spc.MaterialSpecification,
                        ////标准件规格
                        //StandardSpecification = spc.StandardSpecification,
                        //技术条件
                        TechnicalConditions = spc.TechnicalConditions,
                        //材料合格证
                        MaterialCertificate = spc.MaterialCertificate,
                        //协作合格证
                        CooperationCertificate = spc.CooperationCertificate,
                        //供应单位
                        SupplyCompany = spc.SupplyCompany,
                        //非金属制造日期
                        NonMetallicManufacturingDate = spc.NonMetallicManufacturingDate,
                        //非金属压制日期
                        NonMetallicPressingDate = spc.NonMetallicPressingDate,
                        //接收车间
                        InceptWorkshop = spc.InceptWorkshop,
                        #endregion
                        #region 基础信息  
                        //型号(产品代号)
                        ProductCode = string.Join(",", _sysCodeRepository.GetAll().Where(s => productCode.Contains(s.Id.ToString())).Select(s => s.Description)),
                        //型号(产品代号)ID
                        ProductCodeId = spc.ProductCode,
                        //发次
                        SendTime = string.Join(",", _sysCodeRepository.GetAll().Where(s => sendTime.Contains(s.Id.ToString())).Select(s => s.Description)),
                        //发次ID
                        SendTimeId = spc.SendTime,
                        //规格型号
                        Module = spc.Module,
                        //有效期止
                        ExpirationDate = spc.ExpirationDate ?? "2099-01-01T00:00:00.000Z",
                        //单位Id
                        UnitId = (Guid)spc.UnitId,
                        //单位
                        Unit = spc.Unit,
                        //转批次
                        TurnBatch = spc.TurnBatch,
                        //物料属性
                        MaterialsProperty = MaterialsPropertys.正常品,
                        ////入库状态
                        //InputState = StorePutContent.InputStates.待入库,
                        //入库方式
                        WarehousMethod = (StorePutContent.WarehousMethods)spc.WarehousMethod,
                        #endregion
                        AesEncryptData = spc.AesEncryptData,
                        ProductModel = spc.ProductModel
                    };
                    var index = storePutContent.ProductCode.IndexOf("系列");
                    if (index > 0)
                    {
                        storePutContent.SendTime = "全发次";
                        var st = _sysCodeRepository.FirstOrDefault(s => s.Description == "全发次");
                        if (st != null)
                        {
                            storePutContent.SendTimeId = st.Id.ToString().ToUpper();
                        }
                    }
                    await _storePutContentRepository.InsertAsync(storePutContent);
                    StorePutRecord storePutRecord = new StorePutRecord
                    {
                        Id = Guid.NewGuid(),
                        ReleaseOrder = storePutContent.ReleaseOrder,
                        QualifiedNumber = storePutContent.QualifiedNumber,
                        SpecialRecords = storePutContent.SpecialRecords,
                        MaterialsProperty = storePutContent.MaterialsProperty,
                        ProductNumber = storePutContent.ProductNumberShow, //add 11/30
                        QCCardNo = storePutContent.QCCardNo,
                        Quantity = storePutContent.Quantity,
                        BinLocationId = storePutContent.BinLocationId,
                        BinLocation = storePutContent.BinLocation,
                        StorePutPeopleId = storePutContent.StorePutPeopleId,
                        StorePutTime = storePutContent.StorePutTime,
                    };
                    await _storePutRecordRepository.InsertAsync(storePutRecord);
                    _iOperationHistoryAppService.InsertOperationLogNew(storePutContent.Id, BusinessTypes.仓库管理, OperationTypes.仓库新增物料, "增加仓库物料信息");
                    #endregion
                }
                result.code = 0;
                return result;
            }
            catch (Exception ex)
            {
                result.code = 1;
                result.Message = ex.Message;
                return result;
            }
        }
        /// <summary>
        /// 合格证入库信息修改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultMessage> UpdateStorePutContent(StorePutModelContentDto input)
        {
            ResultMessage result = new ResultMessage();
            try
            {
                #region 必填项去除前后空格并判断null值
                if (input.WarehousMethod == 1)
                {
                    input.ReleaseOrder = input.ReleaseOrder.Trim();
                    if (input.ReleaseOrder == null)
                    {
                        result.code = 1;
                        result.Message = "放行单号不能填空格";
                        return result;
                    }
                }
                if (input.WarehousMethod == 0 || input.WarehousMethod == 2)
                {
                    input.QualifiedNumber = input.QualifiedNumber.Trim();
                    if (input.QualifiedNumber == null)
                    {
                        result.code = 1;
                        result.Message = "合格证号不能填空格";
                        return result;
                    }
                }
                input.ProductDrawingNo = input.ProductDrawingNo.Trim();
                if (input.ProductDrawingNo == null)
                {
                    result.code = 1;
                    result.Message = "产品图号不能填空格";
                    return result;
                }
                input.ProductDrawingNo = input.ProductDrawingNo.ToUpper();
                input.ProductName = input.ProductName.Trim();
                if (input.ProductName == null)
                {
                    result.code = 1;
                    result.Message = "产品名称不能填空格";
                    return result;
                }
                input.Batch = input.Batch.Trim();
                if (input.Batch == null)
                {
                    result.code = 1;
                    result.Message = "批次不能填空格";
                    return result;
                }
                input.Module = input.Module.Trim();
                if (input.Module == null)
                {
                    result.code = 1;
                    result.Message = "规格不能填空格";
                    return result;
                }
                input.Module = input.Module.Replace("X", "x").Replace("*", "x").Replace("×", "x").ToUpper();
                #endregion
                //放行单号不能重复
                if (input.WarehousMethod == 1)
                {
                    var releaseOrder = _storePutContentRepository.FirstOrDefaultAsync(s => s.ReleaseOrder == input.ReleaseOrder && s.Id != input.Id).Result;
                    if (releaseOrder != null)
                    {
                        result.code = 1;
                        result.Message = "放行单号不能重复";
                        return result;
                    }
                }
                if (input.Module == null)
                {
                    result.code = 1;
                    result.Message = "请填写规格";
                    return result;
                }
                //对比数量和产品编号数量
                List<string> productNumberList = new List<string>();
                List<string> productNumberShowList = new List<string>();
                var count = 0;
                if (input.ProductNumber != null)
                {
                    string[] productNumber = input.ProductNumber.Split(",").ToList().Where(d => !string.IsNullOrEmpty(d) && d != "undefined" && d != "").ToArray();
                    count = input.ProductNumber.Split(",").Length;
                    productNumberShowList = new List<string>(productNumber);

                    productNumberList = new List<string>(productNumber);
                    for (int i = 0; i < input.Quantity - productNumber.Length; i++)
                    {
                        productNumberList.Add("undefined");
                    }
                }
                else
                {
                    for (int i = 0; i < input.Quantity; i++)
                    {
                        productNumberList.Add("undefined");
                    }
                }
                if (input.Quantity == 0 || input.Quantity < count)
                {
                    result.code = 1;
                    result.Message = "合格证上的数量不能为0或者比产品编号的个数少";
                    return result;
                }
                var storePutContenRole = _storePutContentRepository.FirstOrDefaultAsync(t => t.Id == input.Id).Result;
                var nodeCategory = _materialsNodeRepository.FirstOrDefault(s => s.MaterialTypeName == input.MaterialCategory && s.LevelNum == 2);
                var node = _materialsNodeRepository.FirstOrDefault(s => s.MaterialTypeName == input.MaterialsNode && s.LevelNum == 1);
                if (storePutContenRole.CreatorUserId != GetCurrentUser().Id) //add 11/30
                {
                    result.code = 1;
                    result.Message = "非本人创建，不能修改！";
                    return result;
                }
                List<string> sendTime = new List<string>(input.SendTime.Split(',').ToArray());
                List<string> productCode = new List<string>(input.ProductCode.Split(',').ToArray());
                #region 根据图号、规格 判断物料详细表中是否存在 更新物料信息
                var queryStoreContent = _storePutContentRepository.FirstOrDefault(t => t.QualifiedNumber == input.QualifiedNumber);
                var productDrawingNo = input.ProductDrawingNo;
                var materialType = _materialsNodeRepository.FirstOrDefault(d => d.Id == input.MaterialsNodeId);
                if (productDrawingNo.IndexOf("-") >= 0 && materialType.MaterialTypeName == "标准件")
                {
                    #region 年代号校验
                    var year = input.ProductDrawingNo.Substring(input.ProductDrawingNo.LastIndexOf("-") + 1);
                    if (!string.IsNullOrEmpty(year))
                    {
                        int yearCount = year.Length;
                        if (yearCount == 2 || yearCount == 4)
                        {
                            try
                            {
                                int.Parse(year);
                            }
                            catch
                            {
                                result.code = 1;
                                result.Message = "图号-年代号不正确";
                                return result;
                            }
                        }
                        else
                        {
                            result.code = 1;
                            result.Message = "图号-年代号不正确";
                            return result;
                        }
                    }
                    #endregion
                    productDrawingNo = input.ProductDrawingNo.Substring(0, input.ProductDrawingNo.LastIndexOf("-"));
                }

                var queryMaterialsContents = _materialsContentRepository.FirstOrDefault(t => t.MaterialNo == productDrawingNo && t.Model == input.Module);
                if (queryMaterialsContents.IsUsed == 0)
                {
                    result.code = 1;
                    result.Message = "该物料已经停用";
                    return result;
                }
                //如果存在，那就修改 如果添加成功后，一般不会有不存在的情况
                StoreReturnIdDto storeReturnIdDto = new StoreReturnIdDto();
                if (queryMaterialsContents == null)
                {
                    storeReturnIdDto = await CreateMaterialsContentByStore(input);
                }
                if (queryMaterialsContents != null)
                {
                    var nodeName = _materialsNodeRepository.FirstOrDefault(s => s.Id == queryMaterialsContents.MaterialsNodeId).MaterialTypeName;
                    var categoryName = _materialsNodeRepository.FirstOrDefault(s => s.Id == queryMaterialsContents.MaterialCategoryId).MaterialTypeName;
                    if (nodeName != input.MaterialsNode && categoryName != input.MaterialCategory)
                    {
                        result.code = 1;
                        result.Message = "物料分类、细类与物料详细信息不符；物料分类：" + nodeName + "，物料细类：" + categoryName;
                        return result;
                    }
                }
                #endregion
                #region 合格证信息更新
                #region  仓库信息
                //入库单号
                storePutContenRole.StorePutNo = input.StorePutNo;
                ////仓库Id
                //storePutContenRole.StoreId = input.StoreId;
                ////仓库名称
                //storePutContenRole.StroeName = input.StroeName;
                // 储位ID
                storePutContenRole.BinLocationId = input.BinLocationId;
                // 储位
                storePutContenRole.BinLocation = input.BinLocation;
                //物料细料ID
                if (storeReturnIdDto.MaterialsContentId != null)
                {
                    storePutContenRole.MaterialsContentId = (Guid)storeReturnIdDto.MaterialsContentId;
                }
                else
                {
                    storePutContenRole.MaterialsContentId = queryMaterialsContents.Id;
                }
                //放行单号
                storePutContenRole.ReleaseOrder = input.ReleaseOrder;
                //备注
                storePutContenRole.Remark = input.Remark;
                //物料入库状态 0待入库、1已入库
                storePutContenRole.StoreStateContent = (StoreState)input.StoreStateContent;
                //入库人Id
                storePutContenRole.StorePutPeopleId = GetCurrentUser().Id; //add 11/30
                //入库时间
                storePutContenRole.StorePutTime = storePutContenRole.StorePutTime;
                #endregion

                #region 合格证信息 
                //合格证号
                storePutContenRole.QualifiedNumber = input.QualifiedNumber;
                //产品图号
                storePutContenRole.ProductDrawingNo = input.ProductDrawingNo;
                //产品名称
                storePutContenRole.ProductName = input.ProductName;
                //批次
                storePutContenRole.Batch = input.Batch;
                //合格证号任务
                storePutContenRole.QualifiedTaskNumber = input.QualifiedTaskNumber;
                //数量
                storePutContenRole.Quantity = input.Quantity;
                //产品编号(件号)
                storePutContenRole.ProductNumber = string.Join(",", productNumberList.ToArray());
                storePutContenRole.ProductNumberShow = string.Join(",", productNumberShowList.ToArray());
                //产品编号生成方式 0：自动带出，1：手动输入， 3：自动生成
                storePutContenRole.ProductNumberType = (StorePutContent.ProductNumberTypes)input.ProductNumberType;
                //特殊记载
                storePutContenRole.SpecialRecords = input.SpecialRecords;
                var userId = GetCurrentUser().Id; //add 11/30
                if (input.WarehousMethod == 2 && input.NonMetallicPressingDate == null)
                {

                    storePutContenRole.MaterialBrandStatus = input.MaterialGrade + "/" + input.MaterialStatus + "/" + input.MaterialSpecification;
                    storePutContenRole.NonmetallicMaterialsBrand = null;
                }
                if (input.WarehousMethod == 2 && input.NonMetallicPressingDate != null)
                {
                    storePutContenRole.MaterialBrandStatus = null;
                    storePutContenRole.NonmetallicMaterialsBrand = input.MaterialGrade + "/" + input.MaterialStatus + "/" + input.MaterialSpecification;
                }
                //炉(批)号
                storePutContenRole.HeatNumber = input.HeatNumber;
                //化(试)验号
                storePutContenRole.Mthd = input.Mthd;
                //批次号
                storePutContenRole.BatchNo = input.BatchNo;
                //压制日期
                storePutContenRole.SuppressionDate = input.SuppressionDate;
                //处理技术问题文件编号
                storePutContenRole.DocumentNo = input.DocumentNo;
                //制造车间
                storePutContenRole.ManufacturingWorkshop = input.ManufacturingWorkshop;
                //生产工人
                storePutContenRole.ProductionWorkers = input.ProductionWorkers;
                //工(组)长
                storePutContenRole.Foreman = input.Foreman;
                //检验员
                storePutContenRole.Inspector = input.Inspector;
                //日期
                storePutContenRole.Date = input.Date;
                //质控卡号
                storePutContenRole.QCCardNo = input.QCCardNo;
                //装配任务号
                storePutContenRole.AssemblyTaskNumber = input.AssemblyTaskNumber;
                //阶段标记
                storePutContenRole.StageMark = input.StageMark;
                //材料牌号
                storePutContenRole.MaterialGrade = input.MaterialGrade;
                //材料状态
                storePutContenRole.MaterialStatus = input.MaterialStatus;
                ////材料规格
                //storePutContenRole.MaterialSpecification = input.MaterialSpecification;
                ////标准件规格
                //storePutContenRole.StandardSpecification = input.StandardSpecification;
                //技术条件
                storePutContenRole.TechnicalConditions = input.TechnicalConditions;
                //材料合格证
                storePutContenRole.MaterialCertificate = input.MaterialCertificate;
                //供应单位协作合格证
                storePutContenRole.CooperationCertificate = input.CooperationCertificate;
                //供应单位
                storePutContenRole.SupplyCompany = input.SupplyCompany;
                //非金属制造日期
                storePutContenRole.NonMetallicManufacturingDate = input.NonMetallicManufacturingDate;
                //非金属压制日期
                storePutContenRole.NonMetallicPressingDate = input.NonMetallicPressingDate;
                #endregion

                #region 基础信息  
                //型号(产品代号)
                storePutContenRole.ProductCode = string.Join(",", _sysCodeRepository.GetAll().Where(s => productCode.Contains(s.Id.ToString())).Select(s => s.Description));
                storePutContenRole.ProductCodeId = input.ProductCode;
                //发次
                var index = storePutContenRole.ProductCode.IndexOf("系列");
                if (index > 0)
                {
                    storePutContenRole.SendTime = "全发次";
                    var st = _sysCodeRepository.FirstOrDefault(s => s.Description == "全发次");
                    if (st != null)
                    {
                        storePutContenRole.SendTimeId = st.Id.ToString().ToUpper();
                    }
                }
                else
                {
                    storePutContenRole.SendTime = string.Join(",", _sysCodeRepository.GetAll().Where(s => sendTime.Contains(s.Id.ToString())).Select(s => s.Description));
                    storePutContenRole.SendTimeId = input.SendTime;
                }
                //规格型号
                storePutContenRole.Module = input.Module;
                //有效期止
                storePutContenRole.ExpirationDate = input.ExpirationDate ?? "2099-01-01T00:00:00.000Z";
                //单位Id
                storePutContenRole.UnitId = (Guid)input.UnitId;
                //单位
                storePutContenRole.Unit = input.Unit;
                //转批次
                storePutContenRole.TurnBatch = input.TurnBatch;
                //物料属性
                storePutContenRole.MaterialsProperty = (MaterialsPropertys)input.MaterialsProperty;
                ////入库状态
                //storePutContenRole.InputState = (StorePutContent.InputStates)input.InputState;
                //入库方式
                storePutContenRole.WarehousMethod = (StorePutContent.WarehousMethods)input.WarehousMethod;
                _iOperationHistoryAppService.InsertOperationLogNew(storePutContenRole.Id, BusinessTypes.仓库管理, OperationTypes.仓库修改物料, "修改仓库物料信息");
                //_iOperationHistoryAppService.InsertOperationLog(storePutContenRole.Id, 6, 20, "修改仓库物料信息");
                #endregion
                await _storePutContentRepository.UpdateAsync(storePutContenRole);
                var storePutRecord = _storePutRecordRepository.FirstOrDefaultAsync(s => s.Id == input.StorePutRecordId).Result;
                storePutRecord.ReleaseOrder = storePutContenRole.ReleaseOrder;
                storePutRecord.QualifiedNumber = storePutContenRole.QualifiedNumber;
                storePutRecord.SpecialRecords = storePutContenRole.SpecialRecords;
                storePutRecord.MaterialsProperty = storePutContenRole.MaterialsProperty;
                storePutRecord.ProductNumber = storePutContenRole.ProductNumber;
                storePutRecord.QCCardNo = storePutContenRole.QCCardNo;
                storePutRecord.Quantity = storePutContenRole.Quantity;
                storePutRecord.BinLocationId = storePutContenRole.BinLocationId;
                storePutRecord.BinLocation = storePutContenRole.BinLocation;
                storePutRecord.StorePutPeopleId = storePutContenRole.StorePutPeopleId;
                storePutRecord.StorePutTime = storePutContenRole.StorePutTime;
                await _storePutRecordRepository.UpdateAsync(storePutRecord);
                #endregion
                result.code = 0;
                return result;
            }
            catch (Exception ex)
            {
                result.code = 1;
                result.Message = ex.Message;
                return result;
            }
        }
        /// <summary>
        /// 确认入库
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task NotarizePutStore(StorePutModelContentDto input)
        {
            #region 权限控制,只有仓库人员能确认入库
            var userId = GetCurrentUser().Id; //add 11/30
            var userOrganizationUnit = _userOrganizationUnitRepository.GetAll();
            var organizationUnitList = from ou in _organizationUnitRepository.GetAll().Where(s => s.DisplayName == "仓库人员")
                                       join uou in userOrganizationUnit
                                       on ou.Id equals uou.OrganizationUnitId
                                       where uou.UserId == userId
                                       select ou;
            if (organizationUnitList == null)
            {
                throw new UserFriendlyException("只有仓库人员能确认入库");
            }
            #endregion
            if (input != null)
            {
                var queryStorePutContents = _storePutContentRepository.FirstOrDefaultAsync(t => t.Id == input.Id).Result;
                //var storePutContents = ObjectMapper.Map(input, queryStorePutContents);
                var materialsContent = _storeStockRepository.FirstOrDefault(s => s.MaterialsContentId == queryStorePutContents.MaterialsContentId && s.StoreId == input.StoreId);
                var storeStockId = Guid.Empty;
                queryStorePutContents.StoreId = input.StoreId;//仓库ID
                queryStorePutContents.StroeName = input.StroeName;//仓库
                queryStorePutContents.BinLocationId = input.BinLocationId;//储位ID
                queryStorePutContents.BinLocation = input.BinLocation;//储位
                queryStorePutContents.StoreStateContent = StoreState.已入库;//状态
                queryStorePutContents.IdentifyingPeopleId = userId;//暂时写死 
                queryStorePutContents.IdentifyingTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//确认时间
                await _storePutContentRepository.UpdateAsync(queryStorePutContents);
                var productDrawingNo = input.ProductDrawingNo;
                var year = "";
                var materialsNode = _materialsNodeRepository.FirstOrDefault(d => d.Id == input.MaterialsNodeId);
                if (productDrawingNo.IndexOf("-") >= 0 && materialsNode.MaterialTypeName == "标准件")
                {
                    productDrawingNo = input.ProductDrawingNo.Substring(0, input.ProductDrawingNo.LastIndexOf("-"));
                    year = input.ProductDrawingNo.Substring(input.ProductDrawingNo.LastIndexOf("-") + 1);
                }
                #region 库存信息入库
                if (materialsContent == null)
                {
                    StoreStock storeStock = new StoreStock()
                    {
                        Id = Guid.NewGuid(),
                        CreatorUserId = userId,
                        CreationTime = DateTime.Now,
                        // 物料细料ID
                        MaterialsContentId = (Guid)input.MaterialsContentId,
                        // 仓库ID
                        StoreId = input.StoreId.Value,
                        // 仓库名称
                        StroeName = input.StroeName,
                        // 产品图号
                        ProductDrawingNo = productDrawingNo,
                        // 产品名称
                        ProductName = input.ProductName,
                        // 批次
                        Batch = input.Batch,
                        //规格
                        Module = input.Module,
                        ////转批次
                        //TurnBatch = input.TurnBatch,
                        // 总数量
                        TotalQuantity = input.Quantity,
                        // 库存数量
                        StoreQuantity = input.Quantity,
                        // 产品编号(件号)
                        ProductNumber = queryStorePutContents.ProductNumberShow,
                        // 库存产品编号(件号)
                        StoreProductNumber = queryStorePutContents.ProductNumberShow,
                    };
                    storeStockId = _storeStockRepository.InsertAndGetId(storeStock);
                }
                if (materialsContent != null)
                {
                    // 总数量
                    materialsContent.TotalQuantity = materialsContent.TotalQuantity + input.Quantity;
                    // 库存数量
                    materialsContent.StoreQuantity = materialsContent.StoreQuantity + input.Quantity;
                    if (!string.IsNullOrEmpty(queryStorePutContents.ProductNumberShow))
                    {
                        if (!string.IsNullOrEmpty(materialsContent.ProductNumber))
                        {
                            // 产品编号(件号)
                            materialsContent.ProductNumber = materialsContent.ProductNumber + "," + queryStorePutContents.ProductNumberShow;
                        }
                        else
                        {
                            materialsContent.ProductNumber = queryStorePutContents.ProductNumberShow;
                        }
                        if (!string.IsNullOrEmpty(materialsContent.StoreProductNumber))
                        {
                            // 库存产品编号(件号)
                            materialsContent.StoreProductNumber = materialsContent.StoreProductNumber + "," + queryStorePutContents.ProductNumberShow;

                        }
                        else
                        {
                            materialsContent.StoreProductNumber = queryStorePutContents.ProductNumberShow;
                        }
                    }

                    storeStockId = _storeStockRepository.InsertOrUpdateAndGetId(materialsContent);
                }
                #endregion

                #region 库存详细信息入库
                string[] productNumbers = queryStorePutContents.ProductNumber.Split(',');
                for (var i = 0; i < input.Quantity; i++)
                {
                    var materialsProperty = MaterialsPropertys.正常品;
                    if (input.MaterialsProperty == 4)
                    {
                        materialsProperty = MaterialsPropertys.返修正常品;
                    }
                    var sendTimeLength = input.SendTime.Split(',').Count();
                    string productNumber = null;
                    if (productNumbers[i] != "undefined") productNumber = productNumbers[i].ToString();
                    StoreStockContent storeStockContent = new StoreStockContent()
                    {
                        Id = Guid.NewGuid(),
                        // 库存主表ID
                        StoreStockId = storeStockId,
                        // 合格证入库Id
                        StorePutContentId = input.Id,
                        // 物料细料ID
                        MaterialsContentId = (Guid)input.MaterialsContentId,
                        // 仓库ID
                        StoreId = input.StoreId.Value,
                        // 仓库名称
                        StroeName = input.StroeName,
                        //储位ID
                        BinLocationId = input.BinLocationId,
                        // 储位
                        BinLocation = input.BinLocation,
                        // 放行单号
                        ReleaseOrder = input.ReleaseOrder,
                        // 合格证号
                        QualifiedNumber = input.QualifiedNumber,
                        // 产品编号(件号)
                        ProductNumber = productNumber,
                        //产品图号
                        ProductDrawingNo = productDrawingNo,
                        //产品图号(包含年代)
                        ProductDrawingNoTwo = input.ProductDrawingNo,
                        //年代号
                        Years = year,
                        // 产品名称
                        ProductName = input.ProductName,
                        //规格
                        Module = input.Module,
                        // 型号(产品代号)
                        ProductCode = queryStorePutContents.ProductCode,
                        ProductCodeId = input.ProductCode,
                        // 发次
                        SendTime = queryStorePutContents.SendTime,
                        SendTimeId = input.SendTime,
                        //发次长度
                        SendTimeLength = sendTimeLength,
                        // 批次
                        Batch = input.Batch,
                        //有效期止
                        ExpirationDate = input.ExpirationDate ?? "2099-01-01T00:00:00.000Z",
                        // 是否预配套
                        IsPreSuit = 0,
                        // 是否配套
                        IsSuit = 0,
                        MaterialsProperty = materialsProperty,
                    };
                    await _storeStockContentRepository.InsertAsync(storeStockContent);
                    #endregion
                }
                _iOperationHistoryAppService.InsertOperationLogNew(queryStorePutContents.Id, BusinessTypes.仓库管理, OperationTypes.仓库物料入库, "确认入库");
                //_iOperationHistoryAppService.InsertOperationLog(queryStorePutContents.Id, 6, 21, "确认入库");
            }

        }
        /// <summary>
        /// 批量入库确
        /// </summary>
        /// <param name="input"></param>
        /// <param name="stroeName"></param>
        /// <param name="storeId"></param>
        /// <param name="binLocation"></param>
        /// <param name="binLocationId"></param>
        /// <returns></returns>
        public async Task<ResultMessage> NotarizePutStoreBatch(List<StorePutModelContentDto> input, string stroeName, Guid storeId, string binLocation, Guid binLocationId)
        {
            ResultMessage result = new ResultMessage();
            try
            {
                foreach (var item in input)
                {
                    item.StroeName = stroeName;
                    item.StoreId = storeId;
                    item.BinLocation = binLocation;
                    item.BinLocationId = binLocationId.ToString();
                    await NotarizePutStore(item);
                    _unitOfWorkManager.Current.SaveChanges();
                }
                result.code = 0;
                return result;
            }
            catch (Exception ex)
            {
                result.code = 1;
                result.Message = ex.Message;
                return result;
            }

        }
        /// <summary>
        /// 合格证入库信息删除
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task DeleteStorePutContent(List<StorePutDeleteDto> input)
        {
            foreach (var item in input)
            {
                var count = await _storePutContentRepository.CountAsync(p => p.Id == item.Id);
                if (count == 0)
                {
                    throw new UserFriendlyException("");
                }
                else
                {
                    var storePutContent = _storePutContentRepository.GetAll().Where(p => p.Id == item.Id).FirstOrDefault();
                    if (storePutContent.StoreStateContent == StoreState.待入库)
                    {
                        var storePutRecord = _storePutRecordRepository.GetAll().Where(s => s.QualifiedNumber == storePutContent.QualifiedNumber && s.ReleaseOrder == storePutContent.ReleaseOrder).FirstOrDefault();
                        if (storePutRecord != null)
                        {
                            await _storePutContentRepository.DeleteAsync(storePutContent);
                            await _storePutRecordRepository.DeleteAsync(storePutRecord);
                        }
                    }
                    else
                    {
                        throw new UserFriendlyException("已入库物料不能取消");
                    }
                }
            }
        }
        /// <summary>
        /// Get接口
        /// </summary>
        /// <param name="url"></param>
        /// <param name="number"></param>
        /// <returns></returns>
        private string GetStoreApp(string url, string name, string number)
        {
            string query = _storeHttp.HttpGetData(url + "?" + "number=" + number);
            return query;
        }

        [HttpPost]
        public string PostStoreApp(string url, string postdata)
        {
            string query = _storeHttp.HttpPostData(url, postdata);
            return query;
        }
        /// <summary>
        /// 入库单号模糊查询
        /// </summary>
        /// <returns></returns>
        public List<string> GetStorePutNoList()
        {
            var storePutNo = _storePutContentRepository.GetAll().Select(p => p.StorePutNo).Where(d => d != null);
            if (storePutNo != null) return storePutNo.Distinct().ToList();
            else return null;
        }
        /// <summary>
        /// 产品图号模糊查询
        /// </summary>
        /// <returns></returns>
        public List<string> GetProductDrawingNoList()
        {
            var productDrawingNo = _storePutContentRepository.GetAll().Select(p => p.ProductDrawingNo).Where(d => d != null);
            if (productDrawingNo != null) return productDrawingNo.Distinct().ToList();
            else return null;
        }
        /// <summary>
        /// 任务编号模糊查询
        /// </summary>
        /// <returns></returns>
        public List<string> GetQualifiedTaskNumberList()
        {
            var qualifiedTaskNumber = _storePutContentRepository.GetAll().Where(d => !string.IsNullOrEmpty(d.QualifiedTaskNumber)).Select(p => p.QualifiedTaskNumber);
            if (qualifiedTaskNumber != null) return qualifiedTaskNumber.Distinct().ToList();
            else return null;
        }
        /// <summary>
        /// 合格证号模糊查询
        /// </summary>
        /// <returns></returns>
        public List<string> GetQualifiedNumberList()
        {
            var qualifiedNumber = _storePutContentRepository.GetAll().Select(p => p.QualifiedNumber).Where(d => d != null).Distinct();
            if (qualifiedNumber != null) return qualifiedNumber.Distinct().ToList();
            else return null;
        }
        /// <summary>
        /// 入库人模糊查询
        /// </summary>
        /// <returns></returns>
        public List<string> GetStorePutPeopleList()
        {
            //var queryStorePutContents = _storePutContentRepository.GetAll();
            var userTemp = _userRepository.GetAll().ToList();
            var userList = from qspc in _storePutContentRepository.GetAll()
                           join ur in userTemp
                           on qspc.CreatorUserId equals ur.Id
                           select ur;
            if (userList != null) return userList.Select(p => p.Surname + p.Name).Distinct().Where(d => d != null).ToList();
            else return null;

        }
        /// <summary>
        /// 根据产品图号查询产品名称
        /// </summary>
        /// <param name="productDrawingNoStr"></param>
        /// <param name="modelStr"></param>
        /// <returns></returns>
        public async Task<string> GetProductName(string productDrawingNoStr, string modelStr)
        {
            if (!string.IsNullOrEmpty(productDrawingNoStr) && !string.IsNullOrEmpty(modelStr))
            {
                var product = _materialsContentRepository.FirstOrDefault(p => p.MaterialNo == productDrawingNoStr && p.Model == modelStr);
                if (product != null)
                {
                    return product.MaterialName;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 手动合格证excel导入
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMessage> GetExcelToStorePut(IFormFile file)
        {
            ResultMessage result = new ResultMessage();
            try
            {
                if (file == null)
                {
                    result.code = 1;
                    result.Message = "没有找到有效文件";
                    return result;
                }
                StringBuilder errorMsg = new StringBuilder();
                // 单元格抬头
                // key：实体对象属性名称，可通过反射获取值
                // value：属性对应的中文注解
                Dictionary<string, string> cellheader = new Dictionary<string, string>
            {
                        { "No", "NO." },
                        { "QualifiedNumber", "合格证号" },
                        { "ProductDrawingNo", "产品图号" },
                        { "ProductName", "产品名称" },
                        { "Batch", "批次" },
                        { "ProductCodeName", "型号(产品代号)" },
                        { "SendTimeName", "发次" },
                        { "MaterialsNode", "物料类别" },
                        { "MaterialCategory", "物料细类" },
                        { "Module", "规格" },
                        { "ExpirationDate", "有效期止" },
                        { "Unit", "单位" },
                        { "QualifiedTaskNumber", "合格证任务号" },
                        { "Quantity", "可用数量" },
                        { "ProductNumber", "可用产品编号(件号)" },
                        { "BinLocation", "储位" },
                        { "StroeName", "仓库" },
                        { "StageMark", "阶段标记" },
                        { "StandardSpecification", "标准件规格" },
                        { "DocumentNo", "技术文件号" },
                        { "SpecialRecords", "特殊记载" },
                        { "MaterialGrade", "材料牌号" },
                        { "MaterialStatus", "材料状态" },
                        { "MaterialSpecification", "材料规格" },
                        { "HeatNumber", "炉(批)号" },
                        { "Mthd", "化(试)验号" },
                        { "TechnicalConditions", "技术条件" },
                        { "CooperationCertificateMaterialCertificate", "材料合格证" },
                        { "CooperationCertificate", "协作合格证" },
                        { "NonMetallicManufacturingDate", "非金属制造日期" },
                        { "NonMetallicPressingDate", "非金属压制日期" },
                        { "SupplyCompany", "供应单位" },
                        { "ManufacturingWorkshop", "制造车间" },
                        { "Date", "开证日期" },
                        { "ProductionWorkers", "生产工人" },
                        { "Foreman", "工(组)长" },
                        { "Inspector", "检验员" },
                        { "Amount", "所有数量" },
                        { "JianNum", "所有产品编号" },
                        { "InceptWorkshop", "接收车间" },
                        { "QCCardNo", "质控卡号" },
            };
                List<StorePutModelContentDto> storePutModelContentDtos = _storeImportToTable.GetExcelList<StorePutModelContentDto>(cellheader, file, out errorMsg);
                var query = storePutModelContentDtos.Where(d => d.QualifiedNumber != null && d.ProductDrawingNo != null && d.ProductName != null).ToList();
                #region 必填项校验
                for (int i = 0; i < query.Count(); i++)
                {
                    StorePutModelContentDto storePutModelContentDto = query[i];
                    string errorMsgStr = "第" + (i + 3) + "行数据检测异常：";
                    bool isHaveNoInputValue = false; // 是否含有未输入项
                    if (string.IsNullOrEmpty(storePutModelContentDto.QualifiedNumber))
                    {
                        errorMsgStr += "合格证号不能为空；";
                        isHaveNoInputValue = true;
                    }
                    if (string.IsNullOrEmpty(storePutModelContentDto.ProductDrawingNo))
                    {
                        errorMsgStr += "产品图号不能为空；";
                        isHaveNoInputValue = true;
                    }
                    if (string.IsNullOrEmpty(storePutModelContentDto.ProductName))
                    {
                        errorMsgStr += "产品名称不能为空；";
                        isHaveNoInputValue = true;
                    }
                    if (string.IsNullOrEmpty(storePutModelContentDto.Batch))
                    {
                        errorMsgStr += "批次不能为空；";
                        isHaveNoInputValue = true;
                    }
                    if (string.IsNullOrEmpty(storePutModelContentDto.ProductCodeName))
                    {
                        errorMsgStr += "型号(产品代号)能为空；";
                        isHaveNoInputValue = true;
                    }
                    if (string.IsNullOrEmpty(storePutModelContentDto.SendTimeName))
                    {
                        errorMsgStr += "发次不能为空；";
                        isHaveNoInputValue = true;
                    }
                    if (string.IsNullOrEmpty(storePutModelContentDto.MaterialsNode))
                    {
                        errorMsgStr += "物料类别不能为空；";
                        isHaveNoInputValue = true;
                    }
                    if (string.IsNullOrEmpty(storePutModelContentDto.MaterialCategory))
                    {
                        errorMsgStr += "物料细类不能为空；";
                        isHaveNoInputValue = true;
                    }
                    if (string.IsNullOrEmpty(storePutModelContentDto.Module))
                    {
                        errorMsgStr += "规格不能为空；";
                        isHaveNoInputValue = true;
                    }
                    if (string.IsNullOrEmpty(storePutModelContentDto.Unit))
                    {
                        errorMsgStr += "单位不能为空；";
                        isHaveNoInputValue = true;
                    }
                    if (storePutModelContentDto.Quantity == 0)
                    {
                        errorMsgStr += "可用数量不能为空或者0；";
                        isHaveNoInputValue = true;
                    }
                    if (isHaveNoInputValue) // 若必填项有值未填
                    {
                        errorMsg.AppendLine(errorMsgStr);
                    }
                }
                if (errorMsg.Length > 0)
                {
                    result.code = 1;
                    result.Message = errorMsg.ToString();
                    return result;
                }
                #endregion
                #region 合格证重复校验，型号发次、物料、分类、细类、单位校验
                for (int i = 0; i < query.Count(); i++)
                {
                    var count = query.Where(s => s.QualifiedNumber == query[i].QualifiedNumber).Count();
                    if (count > 1)
                    {
                        result.code = 1;
                        result.Message = "第" + (i + 3) + "行数据检测异常：合格证不能重复";
                        return result;
                    }
                    //规格里的X*x统一替换成x
                    query[i].Module = query[i].Module.Replace("X", "x").Replace("*", "x").Replace("×", "x");
                    //获取型号Id
                    var productCodeName = query[i].ProductCodeName.Split(',').ToList();
                    var productCode = from sc in _sysCodeRepository.GetAll()
                                      join pc in productCodeName
                                      on sc.Description equals pc
                                      select sc;
                    if (productCodeName.Count() != productCode.Count())
                    {
                        result.code = 1;
                        result.Message = "第" + (i + 3) + "行数据检测异常：填写的型号不正确";
                        return result;
                    }

                    query[i].ProductCode = string.Join(",", productCode.Select(s => s.Id).ToArray()).ToUpper();
                    //获取发次Id
                    var sendTimeName = query[i].SendTimeName.Split(',').ToList();
                    var sendTime = from sc in _sysCodeRepository.GetAll()
                                   join pc in sendTimeName
                                   on sc.Description equals pc
                                   select sc;
                    if (sendTimeName.Count() != sendTime.Count())
                    {
                        result.code = 1;
                        result.Message = "第" + (i + 3) + "行数据检测异常：填写的发次不正确";
                        return result;
                    }
                    query[i].SendTime = string.Join(",", sendTime.Select(s => s.Id).ToArray()).ToUpper();
                    //根据图号、规格确定物料并获取物料分类、细类
                    var materialsNode = _materialsNodeRepository.FirstOrDefault(s => s.MaterialTypeName == query[i].MaterialsNode);
                    var MaterialCategory = _materialsNodeRepository.FirstOrDefault(s => s.MaterialTypeName == query[i].MaterialCategory);
                    var productDrawingNo = query[i].ProductDrawingNo;
                    if (productDrawingNo.IndexOf("-") >= 0 && materialsNode.MaterialTypeName == "标准件")
                    {
                        productDrawingNo = query[i].ProductDrawingNo.Substring(0, query[i].ProductDrawingNo.LastIndexOf("-"));
                    }
                    var materialsContent = _materialsContentRepository.FirstOrDefault(s => s.MaterialNo == productDrawingNo && s.Model == query[i].Module);
                    if (materialsContent != null && materialsNode != null && MaterialCategory != null)
                    {
                        if (materialsContent.MaterialsNodeId == materialsNode.Id && materialsContent.MaterialCategoryId == MaterialCategory.Id)
                        {
                            query[i].MaterialsContentId = materialsContent.Id;
                            query[i].MaterialsNodeId = materialsContent.MaterialsNodeId;
                            query[i].MaterialCategoryId = materialsContent.MaterialCategoryId;
                        }
                        else if (materialsContent.MaterialsNodeId == materialsNode.Id && materialsContent.MaterialCategoryId == Guid.Empty && materialsContent.MaterialsNodeId == MaterialCategory.Id)
                        {
                            query[i].MaterialsContentId = materialsContent.Id;
                            query[i].MaterialsNodeId = materialsContent.MaterialsNodeId;
                            query[i].MaterialCategoryId = materialsContent.MaterialsNodeId;
                        }
                        else
                        {
                            var nodeName = _materialsNodeRepository.FirstOrDefault(s => s.Id == materialsContent.MaterialsNodeId).MaterialTypeName;
                            var categoryName = nodeName;
                            if (materialsContent.MaterialCategoryId != Guid.Empty)
                            {
                                categoryName = _materialsNodeRepository.FirstOrDefault(s => s.Id == materialsContent.MaterialCategoryId).MaterialTypeName;
                            }
                            result.code = 1;
                            result.Message = "第" + (i + 3) + "行数据检测异常：填写的物料分类/细类与该物料不符，物料分类：" + nodeName + "；物料细类：" + categoryName + "；";
                            return result;
                        }
                    }
                    //如果物料建模中没有该物料，则在物料建模中查找分类、细类
                    else
                    {
                        if (materialsNode != null && MaterialCategory != null)
                        {
                            query[i].MaterialsNodeId = materialsNode.Id;
                            query[i].MaterialCategoryId = MaterialCategory.Id;
                        }
                        else
                        {
                            result.code = 1;
                            result.Message = "第" + (i + 3) + "行数据检测异常：填写的物料分类/细类不存在";
                            return result;
                        }
                    }
                    //获取仓库ID、储位ID
                    if (!string.IsNullOrEmpty(query[i].StroeName))
                    {
                        var store = _storeContentrepository.FirstOrDefault(s => s.StroeName == query[i].StroeName);
                        if (store != null)
                        {
                            query[i].StoreId = store.Id;
                        }
                        else
                        {
                            result.code = 1;
                            result.Message = "第" + (i + 3) + "行数据检测异常：填写的仓库不正确";
                            return result;
                        }
                    }
                    if (!string.IsNullOrEmpty(query[i].BinLocation))
                    {
                        var binLocation = _sysCodeRepository.FirstOrDefault(s => s.Description == query[i].BinLocation);
                        if (binLocation != null)
                        {
                            query[i].BinLocationId = binLocation.Id.ToString();
                        }
                        else
                        {
                            result.code = 1;
                            result.Message = "第" + (i + 3) + "行数据检测异常：填写的储位不正确";
                            return result;
                        }
                    }
                    //获取单位ID
                    var unit = _sysCodeRepository.FirstOrDefault(s => s.Description == query[i].Unit);
                    if (unit != null)
                    {
                        query[i].UnitId = unit.Id;
                    }
                    else
                    {
                        result.code = 1;
                        result.Message = "第" + (i + 3) + "行数据检测异常：填写的单位不正确";
                        return result;
                    }
                }
                #endregion
                //入库保存
                result = await CreateStorePutContent(query, Guid.Parse("00000000-0000-0000-0000-000000000000"));
                return result;
            }
            catch (Exception ex)
            {
                result.code = 1;
                result.Message = ex.Message;
                return result;
            }
        }
        /// <summary>
        /// 标准件图号中的年代号校验
        /// </summary>
        /// <param name="productDrawingNo"></param>
        /// <param name="materialsNodeId"></param>
        /// <returns></returns>
        public bool CheckYearsNo(string productDrawingNo, Guid materialsNodeId)
        {
            var materialsNode = _materialsNodeRepository.FirstOrDefault(s => s.Id == materialsNodeId);
            if (materialsNode.MaterialTypeName != "标准件")
            {
                return true;
            }
            var year = productDrawingNo.Substring(productDrawingNo.LastIndexOf("-") + 1);
            if (string.IsNullOrEmpty(year))
            {
                return false;
            }
            else
            {
                int yearCount = year.Length;
                if (yearCount == 2 || yearCount == 4)
                {
                    try
                    {
                        int.Parse(year);
                        return true;
                    }
                    catch
                    {
                        return false;
                    }
                }
                return false;
            }
        }
        /// <summary>
        /// 解密数据提取接口
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public async Task<StorePutModelContentDto> GetDataByAesEncrypt(string str)
        {
            var data = _commonAppServiceRepository.AesDecrypt(str, "hahahahahahahaha");
            var arrayData = data.Split("@");
            StorePutModelContentDto storePutModelContentDto = new StorePutModelContentDto();
            //型号
            storePutModelContentDto.ProductCodeName = arrayData[0];
            var productCodeList = from sc in _sysCodeRepository.GetAll().Where(s => s.IsUsed == 1)
                                  join scc in _sysCodeRepository.GetAll()
                                  on sc.PPtr equals scc.Id
                                  where scc.Description == "型号"
                                  select sc;
            if (!string.IsNullOrEmpty(storePutModelContentDto.ProductCodeName))
            {
                var productCode = productCodeList.FirstOrDefault(s => s.Description == storePutModelContentDto.ProductCodeName);
                if (productCode != null) storePutModelContentDto.ProductCode = productCode.Id.ToString();
            }
            //批次
            storePutModelContentDto.Batch = arrayData[1];
            //产品图号(代号)
            storePutModelContentDto.ProductDrawingNo = arrayData[2];
            storePutModelContentDto.Module = "-";
            var materialsContent = _materialsContentRepository.FirstOrDefault(s => s.MaterialNo == storePutModelContentDto.ProductDrawingNo && s.Model == "-");
            if (materialsContent != null)
            {
                storePutModelContentDto.MaterialsNodeId = materialsContent.MaterialsNodeId;
                storePutModelContentDto.MaterialCategoryId = materialsContent.MaterialCategoryId;

            }
            //产品名称
            storePutModelContentDto.ProductName = arrayData[3];
            //阶段
            storePutModelContentDto.StageMark = arrayData[4];
            //产品编码
            storePutModelContentDto.ProductNumber = arrayData[5];
            //数量
            storePutModelContentDto.Quantity = int.Parse(arrayData[6]);
            //生产单位
            storePutModelContentDto.SupplyCompany = arrayData[7];
            //出厂日期
            //storePutModelContentDto.SupplyCompany = arrayData[8];
            //合格证号
            storePutModelContentDto.QualifiedNumber = arrayData[9];
            //储存期(有效期止)
            storePutModelContentDto.ExpirationDate = arrayData[10];
            //校验期
            storePutModelContentDto.Date = arrayData[11];
            //保管期
            //storePutModelContentDto.Date = arrayData[12];
            //保特殊记载
            storePutModelContentDto.SpecialRecords = arrayData[13];
            storePutModelContentDto.AesEncryptData = data;
            //产品标识码
            //storePutModelContentDto.SpecialRecords = arrayData[14];
            return storePutModelContentDto;
        }
        /// <summary>
        /// 标准图号库新增
        /// </summary>
        /// <param name="productNo"></param>
        /// <returns></returns>
        public async Task<ResultMessage> CreateStandardNo(string productNo)
        {
            ResultMessage result = new ResultMessage();
            try
            {
                if (!string.IsNullOrEmpty(productNo))
                {
                    var array = productNo.Split(',');
                    for (int i = 0; i < array.Count(); i++)
                    {
                        var drawingNo = _standardDrawingNoRepository.FirstOrDefault(s => s.Code == array[i]);
                        if (drawingNo == null)
                        {
                            StandardDrawingNo standardDrawingNo = new StandardDrawingNo();
                            standardDrawingNo.Id = Guid.NewGuid();
                            standardDrawingNo.Code = array[i];
                            await _standardDrawingNoRepository.InsertAsync(standardDrawingNo);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result.code = 1;
                result.Message = ex.Message;
                return result;
            }
            result.code = 0;
            return result;
        }
    }
}

